babylon.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. var scene = this._mesh.getScene();
  101. for (var index = 0; index < scene.meshes.length; index++) {
  102. var otherMesh = scene.meshes[index];
  103. if (!otherMesh.material) {
  104. continue;
  105. }
  106. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  107. continue;
  108. }
  109. if (otherMesh.material.getEffect() === effect) {
  110. otherMesh.computeBonesUsingShaders = false;
  111. }
  112. else if (otherMesh.subMeshes) {
  113. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  114. var subMesh = _a[_i];
  115. var subMeshEffect = subMesh.effect;
  116. if (subMeshEffect === effect) {
  117. otherMesh.computeBonesUsingShaders = false;
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. else {
  125. var currentFallbacks = this._defines[this._currentRank];
  126. if (currentFallbacks) {
  127. for (var index = 0; index < currentFallbacks.length; index++) {
  128. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  129. }
  130. }
  131. this._currentRank++;
  132. }
  133. return currentDefines;
  134. };
  135. return EffectFallbacks;
  136. }());
  137. BABYLON.EffectFallbacks = EffectFallbacks;
  138. /**
  139. * Options to be used when creating an effect.
  140. */
  141. var EffectCreationOptions = /** @class */ (function () {
  142. function EffectCreationOptions() {
  143. }
  144. return EffectCreationOptions;
  145. }());
  146. BABYLON.EffectCreationOptions = EffectCreationOptions;
  147. /**
  148. * Effect containing vertex and fragment shader that can be executed on an object.
  149. */
  150. var Effect = /** @class */ (function () {
  151. /**
  152. * Instantiates an effect.
  153. * An effect can be used to create/manage/execute vertex and fragment shaders.
  154. * @param baseName Name of the effect.
  155. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  156. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  157. * @param samplers List of sampler variables that will be passed to the shader.
  158. * @param engine Engine to be used to render the effect
  159. * @param defines Define statements to be added to the shader.
  160. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  161. * @param onCompiled Callback that will be called when the shader is compiled.
  162. * @param onError Callback that will be called if an error occurs during shader compilation.
  163. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  164. */
  165. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  166. if (samplers === void 0) { samplers = null; }
  167. if (defines === void 0) { defines = null; }
  168. if (fallbacks === void 0) { fallbacks = null; }
  169. if (onCompiled === void 0) { onCompiled = null; }
  170. if (onError === void 0) { onError = null; }
  171. var _this = this;
  172. /**
  173. * Unique ID of the effect.
  174. */
  175. this.uniqueId = 0;
  176. /**
  177. * Observable that will be called when the shader is compiled.
  178. */
  179. this.onCompileObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called if an error occurs during shader compilation.
  182. */
  183. this.onErrorObservable = new BABYLON.Observable();
  184. /**
  185. * Observable that will be called when effect is bound.
  186. */
  187. this.onBindObservable = new BABYLON.Observable();
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "key", {
  267. /**
  268. * Unique key for this effect
  269. */
  270. get: function () {
  271. return this._key;
  272. },
  273. enumerable: true,
  274. configurable: true
  275. });
  276. /**
  277. * If the effect has been compiled and prepared.
  278. * @returns if the effect is compiled and prepared.
  279. */
  280. Effect.prototype.isReady = function () {
  281. return this._isReady;
  282. };
  283. /**
  284. * The engine the effect was initialized with.
  285. * @returns the engine.
  286. */
  287. Effect.prototype.getEngine = function () {
  288. return this._engine;
  289. };
  290. /**
  291. * The compiled webGL program for the effect
  292. * @returns the webGL program.
  293. */
  294. Effect.prototype.getProgram = function () {
  295. return this._program;
  296. };
  297. /**
  298. * The set of names of attribute variables for the shader.
  299. * @returns An array of attribute names.
  300. */
  301. Effect.prototype.getAttributesNames = function () {
  302. return this._attributesNames;
  303. };
  304. /**
  305. * Returns the attribute at the given index.
  306. * @param index The index of the attribute.
  307. * @returns The location of the attribute.
  308. */
  309. Effect.prototype.getAttributeLocation = function (index) {
  310. return this._attributes[index];
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param name of the attribute to look up.
  315. * @returns the attribute location.
  316. */
  317. Effect.prototype.getAttributeLocationByName = function (name) {
  318. var index = this._attributesNames.indexOf(name);
  319. return this._attributes[index];
  320. };
  321. /**
  322. * The number of attributes.
  323. * @returns the numnber of attributes.
  324. */
  325. Effect.prototype.getAttributesCount = function () {
  326. return this._attributes.length;
  327. };
  328. /**
  329. * Gets the index of a uniform variable.
  330. * @param uniformName of the uniform to look up.
  331. * @returns the index.
  332. */
  333. Effect.prototype.getUniformIndex = function (uniformName) {
  334. return this._uniformsNames.indexOf(uniformName);
  335. };
  336. /**
  337. * Returns the attribute based on the name of the variable.
  338. * @param uniformName of the uniform to look up.
  339. * @returns the location of the uniform.
  340. */
  341. Effect.prototype.getUniform = function (uniformName) {
  342. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  343. };
  344. /**
  345. * Returns an array of sampler variable names
  346. * @returns The array of sampler variable neames.
  347. */
  348. Effect.prototype.getSamplers = function () {
  349. return this._samplers;
  350. };
  351. /**
  352. * The error from the last compilation.
  353. * @returns the error string.
  354. */
  355. Effect.prototype.getCompilationError = function () {
  356. return this._compilationError;
  357. };
  358. /**
  359. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  360. * @param func The callback to be used.
  361. */
  362. Effect.prototype.executeWhenCompiled = function (func) {
  363. if (this.isReady()) {
  364. func(this);
  365. return;
  366. }
  367. this.onCompileObservable.add(function (effect) {
  368. func(effect);
  369. });
  370. };
  371. /** @hidden */
  372. Effect.prototype._loadVertexShader = function (vertex, callback) {
  373. if (BABYLON.Tools.IsWindowObjectExist()) {
  374. // DOM element ?
  375. if (vertex instanceof HTMLElement) {
  376. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  377. callback(vertexCode);
  378. return;
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. callback(vertexBinary);
  385. return;
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  389. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  390. return;
  391. }
  392. var vertexShaderUrl;
  393. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  394. vertexShaderUrl = vertex;
  395. }
  396. else {
  397. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  398. }
  399. // Vertex shader
  400. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (fragment instanceof HTMLElement) {
  407. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  408. callback(fragmentCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (fragment.substr(0, 7) === "base64:") {
  414. var fragmentBinary = window.atob(fragment.substr(7));
  415. callback(fragmentBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  420. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  421. return;
  422. }
  423. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  424. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  425. return;
  426. }
  427. var fragmentShaderUrl;
  428. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  429. fragmentShaderUrl = fragment;
  430. }
  431. else {
  432. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  433. }
  434. // Fragment shader
  435. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  436. };
  437. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  438. // Rebuild shaders source code
  439. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  440. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  441. vertexCode = prefix + vertexCode;
  442. fragmentCode = prefix + fragmentCode;
  443. // Number lines of shaders source code
  444. var i = 2;
  445. var regex = /\n/gm;
  446. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  447. i = 2;
  448. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  449. // Dump shaders name and formatted source code
  450. if (this.name.vertexElement) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  453. }
  454. else if (this.name.vertex) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  457. }
  458. else {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  461. }
  462. };
  463. ;
  464. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  465. var preparedSourceCode = this._processPrecision(sourceCode);
  466. if (this._engine.webGLVersion == 1) {
  467. callback(preparedSourceCode);
  468. return;
  469. }
  470. // Already converted
  471. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  472. callback(preparedSourceCode.replace("#version 300 es", ""));
  473. return;
  474. }
  475. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  476. // Remove extensions
  477. // #extension GL_OES_standard_derivatives : enable
  478. // #extension GL_EXT_shader_texture_lod : enable
  479. // #extension GL_EXT_frag_depth : enable
  480. // #extension GL_EXT_draw_buffers : require
  481. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  482. var result = preparedSourceCode.replace(regex, "");
  483. // Migrate to GLSL v300
  484. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  485. result = result.replace(/attribute[ \t]/g, "in ");
  486. result = result.replace(/[ \t]attribute/g, " in");
  487. if (isFragment) {
  488. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  489. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/texture2D\s*\(/g, "texture(");
  491. result = result.replace(/textureCube\s*\(/g, "texture(");
  492. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  493. result = result.replace(/gl_FragColor/g, "glFragColor");
  494. result = result.replace(/gl_FragData/g, "glFragData");
  495. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  496. }
  497. callback(result);
  498. };
  499. Effect.prototype._processIncludes = function (sourceCode, callback) {
  500. var _this = this;
  501. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  502. var match = regex.exec(sourceCode);
  503. var returnValue = new String(sourceCode);
  504. while (match != null) {
  505. var includeFile = match[1];
  506. // Uniform declaration
  507. if (includeFile.indexOf("__decl__") !== -1) {
  508. includeFile = includeFile.replace(/__decl__/, "");
  509. if (this._engine.supportsUniformBuffers) {
  510. includeFile = includeFile.replace(/Vertex/, "Ubo");
  511. includeFile = includeFile.replace(/Fragment/, "Ubo");
  512. }
  513. includeFile = includeFile + "Declaration";
  514. }
  515. if (Effect.IncludesShadersStore[includeFile]) {
  516. // Substitution
  517. var includeContent = Effect.IncludesShadersStore[includeFile];
  518. if (match[2]) {
  519. var splits = match[3].split(",");
  520. for (var index = 0; index < splits.length; index += 2) {
  521. var source = new RegExp(splits[index], "g");
  522. var dest = splits[index + 1];
  523. includeContent = includeContent.replace(source, dest);
  524. }
  525. }
  526. if (match[4]) {
  527. var indexString = match[5];
  528. if (indexString.indexOf("..") !== -1) {
  529. var indexSplits = indexString.split("..");
  530. var minIndex = parseInt(indexSplits[0]);
  531. var maxIndex = parseInt(indexSplits[1]);
  532. var sourceIncludeContent = includeContent.slice(0);
  533. includeContent = "";
  534. if (isNaN(maxIndex)) {
  535. maxIndex = this._indexParameters[indexSplits[1]];
  536. }
  537. for (var i = minIndex; i < maxIndex; i++) {
  538. if (!this._engine.supportsUniformBuffers) {
  539. // Ubo replacement
  540. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  541. return p1 + "{X}";
  542. });
  543. }
  544. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  545. }
  546. }
  547. else {
  548. if (!this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent = includeContent.replace(/\{X\}/g, indexString);
  555. }
  556. }
  557. // Replace
  558. returnValue = returnValue.replace(match[0], includeContent);
  559. }
  560. else {
  561. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  562. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  563. Effect.IncludesShadersStore[includeFile] = fileContent;
  564. _this._processIncludes(returnValue, callback);
  565. });
  566. return;
  567. }
  568. match = regex.exec(sourceCode);
  569. }
  570. callback(returnValue);
  571. };
  572. Effect.prototype._processPrecision = function (source) {
  573. if (source.indexOf("precision highp float") === -1) {
  574. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  575. source = "precision mediump float;\n" + source;
  576. }
  577. else {
  578. source = "precision highp float;\n" + source;
  579. }
  580. }
  581. else {
  582. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  583. source = source.replace("precision highp float", "precision mediump float");
  584. }
  585. }
  586. return source;
  587. };
  588. /**
  589. * Recompiles the webGL program
  590. * @param vertexSourceCode The source code for the vertex shader.
  591. * @param fragmentSourceCode The source code for the fragment shader.
  592. * @param onCompiled Callback called when completed.
  593. * @param onError Callback called on error.
  594. */
  595. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  596. var _this = this;
  597. this._isReady = false;
  598. this._vertexSourceCodeOverride = vertexSourceCode;
  599. this._fragmentSourceCodeOverride = fragmentSourceCode;
  600. this.onError = function (effect, error) {
  601. if (onError) {
  602. onError(error);
  603. }
  604. };
  605. this.onCompiled = function () {
  606. var scenes = _this.getEngine().scenes;
  607. for (var i = 0; i < scenes.length; i++) {
  608. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  609. }
  610. if (onCompiled) {
  611. onCompiled(_this._program);
  612. }
  613. };
  614. this._fallbacks = null;
  615. this._prepareEffect();
  616. };
  617. /**
  618. * Gets the uniform locations of the the specified variable names
  619. * @param names THe names of the variables to lookup.
  620. * @returns Array of locations in the same order as variable names.
  621. */
  622. Effect.prototype.getSpecificUniformLocations = function (names) {
  623. var engine = this._engine;
  624. return engine.getUniforms(this._program, names);
  625. };
  626. /**
  627. * Prepares the effect
  628. */
  629. Effect.prototype._prepareEffect = function () {
  630. var attributesNames = this._attributesNames;
  631. var defines = this.defines;
  632. var fallbacks = this._fallbacks;
  633. this._valueCache = {};
  634. var previousProgram = this._program;
  635. try {
  636. var engine = this._engine;
  637. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  638. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  639. }
  640. else {
  641. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  642. }
  643. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  644. if (engine.supportsUniformBuffers) {
  645. for (var name in this._uniformBuffersNames) {
  646. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  647. }
  648. }
  649. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  650. this._attributes = engine.getAttributes(this._program, attributesNames);
  651. var index;
  652. for (index = 0; index < this._samplers.length; index++) {
  653. var sampler = this.getUniform(this._samplers[index]);
  654. if (sampler == null) {
  655. this._samplers.splice(index, 1);
  656. index--;
  657. }
  658. }
  659. engine.bindSamplers(this);
  660. this._compilationError = "";
  661. this._isReady = true;
  662. if (this.onCompiled) {
  663. this.onCompiled(this);
  664. }
  665. this.onCompileObservable.notifyObservers(this);
  666. this.onCompileObservable.clear();
  667. // Unbind mesh reference in fallbacks
  668. if (this._fallbacks) {
  669. this._fallbacks.unBindMesh();
  670. }
  671. if (previousProgram) {
  672. this.getEngine()._deleteProgram(previousProgram);
  673. }
  674. }
  675. catch (e) {
  676. this._compilationError = e.message;
  677. // Let's go through fallbacks then
  678. BABYLON.Tools.Error("Unable to compile effect:");
  679. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  680. return " " + uniform;
  681. }));
  682. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  683. return " " + attribute;
  684. }));
  685. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  686. BABYLON.Tools.Error("Error: " + this._compilationError);
  687. if (previousProgram) {
  688. this._program = previousProgram;
  689. this._isReady = true;
  690. if (this.onError) {
  691. this.onError(this, this._compilationError);
  692. }
  693. this.onErrorObservable.notifyObservers(this);
  694. }
  695. if (fallbacks && fallbacks.isMoreFallbacks) {
  696. BABYLON.Tools.Error("Trying next fallback.");
  697. this.defines = fallbacks.reduce(this.defines, this);
  698. this._prepareEffect();
  699. }
  700. else { // Sorry we did everything we can
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. this.onErrorObservable.clear();
  706. // Unbind mesh reference in fallbacks
  707. if (this._fallbacks) {
  708. this._fallbacks.unBindMesh();
  709. }
  710. }
  711. }
  712. };
  713. Object.defineProperty(Effect.prototype, "isSupported", {
  714. /**
  715. * Checks if the effect is supported. (Must be called after compilation)
  716. */
  717. get: function () {
  718. return this._compilationError === "";
  719. },
  720. enumerable: true,
  721. configurable: true
  722. });
  723. /**
  724. * Binds a texture to the engine to be used as output of the shader.
  725. * @param channel Name of the output variable.
  726. * @param texture Texture to bind.
  727. */
  728. Effect.prototype._bindTexture = function (channel, texture) {
  729. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  730. };
  731. /**
  732. * Sets a texture on the engine to be used in the shader.
  733. * @param channel Name of the sampler variable.
  734. * @param texture Texture to set.
  735. */
  736. Effect.prototype.setTexture = function (channel, texture) {
  737. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  738. };
  739. /**
  740. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  741. * @param channel Name of the sampler variable.
  742. * @param texture Texture to set.
  743. */
  744. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  745. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  746. };
  747. /**
  748. * Sets an array of textures on the engine to be used in the shader.
  749. * @param channel Name of the variable.
  750. * @param textures Textures to set.
  751. */
  752. Effect.prototype.setTextureArray = function (channel, textures) {
  753. if (this._samplers.indexOf(channel + "Ex") === -1) {
  754. var initialPos = this._samplers.indexOf(channel);
  755. for (var index = 1; index < textures.length; index++) {
  756. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  757. }
  758. }
  759. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  760. };
  761. /**
  762. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  763. * @param channel Name of the sampler variable.
  764. * @param postProcess Post process to get the input texture from.
  765. */
  766. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  767. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  768. };
  769. /**
  770. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  771. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  772. * @param channel Name of the sampler variable.
  773. * @param postProcess Post process to get the output texture from.
  774. */
  775. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  776. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  777. };
  778. /** @hidden */
  779. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  780. var cache = this._valueCache[uniformName];
  781. var flag = matrix.updateFlag;
  782. if (cache !== undefined && cache === flag) {
  783. return false;
  784. }
  785. this._valueCache[uniformName] = flag;
  786. return true;
  787. };
  788. /** @hidden */
  789. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. return changed;
  806. };
  807. /** @hidden */
  808. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  809. var cache = this._valueCache[uniformName];
  810. if (!cache) {
  811. cache = [x, y, z];
  812. this._valueCache[uniformName] = cache;
  813. return true;
  814. }
  815. var changed = false;
  816. if (cache[0] !== x) {
  817. cache[0] = x;
  818. changed = true;
  819. }
  820. if (cache[1] !== y) {
  821. cache[1] = y;
  822. changed = true;
  823. }
  824. if (cache[2] !== z) {
  825. cache[2] = z;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @hidden */
  831. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z, w];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. if (cache[3] !== w) {
  852. cache[3] = w;
  853. changed = true;
  854. }
  855. return changed;
  856. };
  857. /**
  858. * Binds a buffer to a uniform.
  859. * @param buffer Buffer to bind.
  860. * @param name Name of the uniform variable to bind to.
  861. */
  862. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  863. var bufferName = this._uniformBuffersNames[name];
  864. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  865. return;
  866. }
  867. Effect._baseCache[bufferName] = buffer;
  868. this._engine.bindUniformBufferBase(buffer, bufferName);
  869. };
  870. /**
  871. * Binds block to a uniform.
  872. * @param blockName Name of the block to bind.
  873. * @param index Index to bind.
  874. */
  875. Effect.prototype.bindUniformBlock = function (blockName, index) {
  876. this._engine.bindUniformBlock(this._program, blockName, index);
  877. };
  878. /**
  879. * Sets an interger value on a uniform variable.
  880. * @param uniformName Name of the variable.
  881. * @param value Value to be set.
  882. * @returns this effect.
  883. */
  884. Effect.prototype.setInt = function (uniformName, value) {
  885. var cache = this._valueCache[uniformName];
  886. if (cache !== undefined && cache === value)
  887. return this;
  888. this._valueCache[uniformName] = value;
  889. this._engine.setInt(this.getUniform(uniformName), value);
  890. return this;
  891. };
  892. /**
  893. * Sets an int array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setIntArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setIntArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setIntArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setIntArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setIntArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setIntArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setIntArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setIntArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an float array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setFloatArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setFloatArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets an array on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param array array to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setArray = function (uniformName, array) {
  987. this._valueCache[uniformName] = null;
  988. this._engine.setArray(this.getUniform(uniformName), array);
  989. return this;
  990. };
  991. /**
  992. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  993. * @param uniformName Name of the variable.
  994. * @param array array to be set.
  995. * @returns this effect.
  996. */
  997. Effect.prototype.setArray2 = function (uniformName, array) {
  998. this._valueCache[uniformName] = null;
  999. this._engine.setArray2(this.getUniform(uniformName), array);
  1000. return this;
  1001. };
  1002. /**
  1003. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1004. * @param uniformName Name of the variable.
  1005. * @param array array to be set.
  1006. * @returns this effect.
  1007. */
  1008. Effect.prototype.setArray3 = function (uniformName, array) {
  1009. this._valueCache[uniformName] = null;
  1010. this._engine.setArray3(this.getUniform(uniformName), array);
  1011. return this;
  1012. };
  1013. /**
  1014. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setArray4 = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setArray4(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets matrices on a uniform variable.
  1026. * @param uniformName Name of the variable.
  1027. * @param matrices matrices to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1031. if (!matrices) {
  1032. return this;
  1033. }
  1034. this._valueCache[uniformName] = null;
  1035. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets matrix on a uniform variable.
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1045. if (this._cacheMatrix(uniformName, matrix)) {
  1046. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1047. }
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets a float on a uniform variable.
  1074. * @param uniformName Name of the variable.
  1075. * @param value value to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloat = function (uniformName, value) {
  1079. var cache = this._valueCache[uniformName];
  1080. if (cache !== undefined && cache === value)
  1081. return this;
  1082. this._valueCache[uniformName] = value;
  1083. this._engine.setFloat(this.getUniform(uniformName), value);
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a boolean on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param bool value to be set.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setBool = function (uniformName, bool) {
  1093. var cache = this._valueCache[uniformName];
  1094. if (cache !== undefined && cache === bool)
  1095. return this;
  1096. this._valueCache[uniformName] = bool;
  1097. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a Vector2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param vector2 vector2 to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1107. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1108. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1109. }
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param x First float in float2.
  1116. * @param y Second float in float2.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1120. if (this._cacheFloat2(uniformName, x, y)) {
  1121. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector3 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1132. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1133. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float3.
  1141. * @param y Second float in float3.
  1142. * @param z Third float in float3.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1146. if (this._cacheFloat3(uniformName, x, y, z)) {
  1147. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Vector4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param vector4 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1158. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1159. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a float4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param x First float in float4.
  1167. * @param y Second float in float4.
  1168. * @param z Third float in float4.
  1169. * @param w Fourth float in float4.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1173. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setColor3 = function (uniformName, color3) {
  1185. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1186. this._engine.setColor3(this.getUniform(uniformName), color3);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color4 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @param alpha Alpha value to be set.
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1198. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1199. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Color4 on a uniform variable
  1205. * @param uniformName defines the name of the variable
  1206. * @param color4 defines the value to be set
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1210. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1211. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Resets the cache of effects.
  1217. */
  1218. Effect.ResetCache = function () {
  1219. Effect._baseCache = {};
  1220. };
  1221. Effect._uniqueIdSeed = 0;
  1222. Effect._baseCache = {};
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the given ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the given ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the given floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the given floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the given array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the given Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the given array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1942. result.r += this.r * scale;
  1943. result.g += this.g * scale;
  1944. result.b += this.b * scale;
  1945. result.a += this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the given Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the given float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the given float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the given array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. /**
  2196. * Class representing a vector containing 2 coordinates
  2197. */
  2198. var Vector2 = /** @class */ (function () {
  2199. /**
  2200. * Creates a new Vector2 from the given x and y coordinates
  2201. * @param x defines the first coordinate
  2202. * @param y defines the second coordinate
  2203. */
  2204. function Vector2(
  2205. /** defines the first coordinate */
  2206. x,
  2207. /** defines the second coordinate */
  2208. y) {
  2209. this.x = x;
  2210. this.y = y;
  2211. }
  2212. /**
  2213. * Gets a string with the Vector2 coordinates
  2214. * @returns a string with the Vector2 coordinates
  2215. */
  2216. Vector2.prototype.toString = function () {
  2217. return "{X: " + this.x + " Y:" + this.y + "}";
  2218. };
  2219. /**
  2220. * Gets class name
  2221. * @returns the string "Vector2"
  2222. */
  2223. Vector2.prototype.getClassName = function () {
  2224. return "Vector2";
  2225. };
  2226. /**
  2227. * Gets current vector hash code
  2228. * @returns the Vector2 hash code as a number
  2229. */
  2230. Vector2.prototype.getHashCode = function () {
  2231. var hash = this.x || 0;
  2232. hash = (hash * 397) ^ (this.y || 0);
  2233. return hash;
  2234. };
  2235. // Operators
  2236. /**
  2237. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2238. * @param array defines the source array
  2239. * @param index defines the offset in source array
  2240. * @returns the current Vector2
  2241. */
  2242. Vector2.prototype.toArray = function (array, index) {
  2243. if (index === void 0) { index = 0; }
  2244. array[index] = this.x;
  2245. array[index + 1] = this.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Copy the current vector to an array
  2250. * @returns a new array with 2 elements: the Vector2 coordinates.
  2251. */
  2252. Vector2.prototype.asArray = function () {
  2253. var result = new Array();
  2254. this.toArray(result, 0);
  2255. return result;
  2256. };
  2257. /**
  2258. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2259. * @param source defines the source Vector2
  2260. * @returns the current updated Vector2
  2261. */
  2262. Vector2.prototype.copyFrom = function (source) {
  2263. this.x = source.x;
  2264. this.y = source.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Sets the Vector2 coordinates with the given floats
  2269. * @param x defines the first coordinate
  2270. * @param y defines the second coordinate
  2271. * @returns the current updated Vector2
  2272. */
  2273. Vector2.prototype.copyFromFloats = function (x, y) {
  2274. this.x = x;
  2275. this.y = y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Sets the Vector2 coordinates with the given floats
  2280. * @param x defines the first coordinate
  2281. * @param y defines the second coordinate
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.set = function (x, y) {
  2285. return this.copyFromFloats(x, y);
  2286. };
  2287. /**
  2288. * Add another vector with the current one
  2289. * @param otherVector defines the other vector
  2290. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2297. * @param otherVector defines the other vector
  2298. * @param result defines the target vector
  2299. * @returns the unmodified current Vector2
  2300. */
  2301. Vector2.prototype.addToRef = function (otherVector, result) {
  2302. result.x = this.x + otherVector.x;
  2303. result.y = this.y + otherVector.y;
  2304. return this;
  2305. };
  2306. /**
  2307. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2308. * @param otherVector defines the other vector
  2309. * @returns the current updated Vector2
  2310. */
  2311. Vector2.prototype.addInPlace = function (otherVector) {
  2312. this.x += otherVector.x;
  2313. this.y += otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2
  2320. */
  2321. Vector2.prototype.addVector3 = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.subtract = function (otherVector) {
  2330. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2334. * @param otherVector defines the other vector
  2335. * @param result defines the target vector
  2336. * @returns the unmodified current Vector2
  2337. */
  2338. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2339. result.x = this.x - otherVector.x;
  2340. result.y = this.y - otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns the current updated Vector2
  2347. */
  2348. Vector2.prototype.subtractInPlace = function (otherVector) {
  2349. this.x -= otherVector.x;
  2350. this.y -= otherVector.y;
  2351. return this;
  2352. };
  2353. /**
  2354. * Multiplies in place the current Vector2 coordinates by the given ones
  2355. * @param otherVector defines the other vector
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2359. this.x *= otherVector.x;
  2360. this.y *= otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2365. * @param otherVector defines the other vector
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiply = function (otherVector) {
  2369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2370. };
  2371. /**
  2372. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @param result defines the target vector
  2375. * @returns the unmodified current Vector2
  2376. */
  2377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2378. result.x = this.x * otherVector.x;
  2379. result.y = this.y * otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns a new Vector2
  2387. */
  2388. Vector2.prototype.multiplyByFloats = function (x, y) {
  2389. return new Vector2(this.x * x, this.y * y);
  2390. };
  2391. /**
  2392. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.divide = function (otherVector) {
  2397. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.divideToRef = function (otherVector, result) {
  2406. result.x = this.x / otherVector.x;
  2407. result.y = this.y / otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Divides the current Vector3 coordinates by the given ones
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.divideInPlace = function (otherVector) {
  2416. return this.divideToRef(otherVector, this);
  2417. };
  2418. /**
  2419. * Gets a new Vector2 with current Vector2 negated coordinates
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.negate = function () {
  2423. return new Vector2(-this.x, -this.y);
  2424. };
  2425. /**
  2426. * Multiply the Vector2 coordinates by scale
  2427. * @param scale defines the scaling factor
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.scaleInPlace = function (scale) {
  2431. this.x *= scale;
  2432. this.y *= scale;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2437. * @param scale defines the scaling factor
  2438. * @returns a new Vector2
  2439. */
  2440. Vector2.prototype.scale = function (scale) {
  2441. var result = new Vector2(0, 0);
  2442. this.scaleToRef(scale, result);
  2443. return result;
  2444. };
  2445. /**
  2446. * Scale the current Vector2 values by a factor to a given Vector2
  2447. * @param scale defines the scale factor
  2448. * @param result defines the Vector2 object where to store the result
  2449. * @returns the unmodified current Vector2
  2450. */
  2451. Vector2.prototype.scaleToRef = function (scale, result) {
  2452. result.x = this.x * scale;
  2453. result.y = this.y * scale;
  2454. return this;
  2455. };
  2456. /**
  2457. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2458. * @param scale defines the scale factor
  2459. * @param result defines the Vector2 object where to store the result
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2463. result.x += this.x * scale;
  2464. result.y += this.y * scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a boolean if two vectors are equals
  2469. * @param otherVector defines the other vector
  2470. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2471. */
  2472. Vector2.prototype.equals = function (otherVector) {
  2473. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals (using an epsilon value)
  2477. * @param otherVector defines the other vector
  2478. * @param epsilon defines the minimal distance to consider equality
  2479. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2480. */
  2481. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2482. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2483. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2484. };
  2485. // Properties
  2486. /**
  2487. * Gets the length of the vector
  2488. * @returns the vector length (float)
  2489. */
  2490. Vector2.prototype.length = function () {
  2491. return Math.sqrt(this.x * this.x + this.y * this.y);
  2492. };
  2493. /**
  2494. * Gets the vector squared length
  2495. * @returns the vector squared length (float)
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector
  2503. * @returns the current updated Vector2
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Gets a new Vector2 copied from the Vector2
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.clone = function () {
  2519. return new Vector2(this.x, this.y);
  2520. };
  2521. // Statics
  2522. /**
  2523. * Gets a new Vector2(0, 0)
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.Zero = function () {
  2527. return new Vector2(0, 0);
  2528. };
  2529. /**
  2530. * Gets a new Vector2(1, 1)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.One = function () {
  2534. return new Vector2(1, 1);
  2535. };
  2536. /**
  2537. * Gets a new Vector2 set from the given index element of the given array
  2538. * @param array defines the data source
  2539. * @param offset defines the offset in the data source
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.FromArray = function (array, offset) {
  2543. if (offset === void 0) { offset = 0; }
  2544. return new Vector2(array[offset], array[offset + 1]);
  2545. };
  2546. /**
  2547. * Sets "result" from the given index element of the given array
  2548. * @param array defines the data source
  2549. * @param offset defines the offset in the data source
  2550. * @param result defines the target vector
  2551. */
  2552. Vector2.FromArrayToRef = function (array, offset, result) {
  2553. result.x = array[offset];
  2554. result.y = array[offset + 1];
  2555. };
  2556. /**
  2557. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2558. * @param value1 defines 1st point of control
  2559. * @param value2 defines 2nd point of control
  2560. * @param value3 defines 3rd point of control
  2561. * @param value4 defines 4th point of control
  2562. * @param amount defines the interpolation factor
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2566. var squared = amount * amount;
  2567. var cubed = amount * squared;
  2568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2578. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2579. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2580. * @param value defines the value to clamp
  2581. * @param min defines the lower limit
  2582. * @param max defines the upper limit
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Clamp = function (value, min, max) {
  2586. var x = value.x;
  2587. x = (x > max.x) ? max.x : x;
  2588. x = (x < min.x) ? min.x : x;
  2589. var y = value.y;
  2590. y = (y > max.y) ? max.y : y;
  2591. y = (y < min.y) ? min.y : y;
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2596. * @param value1 defines the 1st control point
  2597. * @param tangent1 defines the outgoing tangent
  2598. * @param value2 defines the 2nd control point
  2599. * @param tangent2 defines the incoming tangent
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2604. var squared = amount * amount;
  2605. var cubed = amount * squared;
  2606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2608. var part3 = (cubed - (2.0 * squared)) + amount;
  2609. var part4 = cubed - squared;
  2610. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2611. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2612. return new Vector2(x, y);
  2613. };
  2614. /**
  2615. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2616. * @param start defines the start vector
  2617. * @param end defines the end vector
  2618. * @param amount defines the interpolation factor
  2619. * @returns a new Vector2
  2620. */
  2621. Vector2.Lerp = function (start, end, amount) {
  2622. var x = start.x + ((end.x - start.x) * amount);
  2623. var y = start.y + ((end.y - start.y) * amount);
  2624. return new Vector2(x, y);
  2625. };
  2626. /**
  2627. * Gets the dot product of the vector "left" and the vector "right"
  2628. * @param left defines first vector
  2629. * @param right defines second vector
  2630. * @returns the dot product (float)
  2631. */
  2632. Vector2.Dot = function (left, right) {
  2633. return left.x * right.x + left.y * right.y;
  2634. };
  2635. /**
  2636. * Returns a new Vector2 equal to the normalized given vector
  2637. * @param vector defines the vector to normalize
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Normalize = function (vector) {
  2641. var newVector = vector.clone();
  2642. newVector.normalize();
  2643. return newVector;
  2644. };
  2645. /**
  2646. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2647. * @param left defines 1st vector
  2648. * @param right defines 2nd vector
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.Minimize = function (left, right) {
  2652. var x = (left.x < right.x) ? left.x : right.x;
  2653. var y = (left.y < right.y) ? left.y : right.y;
  2654. return new Vector2(x, y);
  2655. };
  2656. /**
  2657. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2658. * @param left defines 1st vector
  2659. * @param right defines 2nd vector
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Maximize = function (left, right) {
  2663. var x = (left.x > right.x) ? left.x : right.x;
  2664. var y = (left.y > right.y) ? left.y : right.y;
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2669. * @param vector defines the vector to transform
  2670. * @param transformation defines the matrix to apply
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Transform = function (vector, transformation) {
  2674. var r = Vector2.Zero();
  2675. Vector2.TransformToRef(vector, transformation, r);
  2676. return r;
  2677. };
  2678. /**
  2679. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2680. * @param vector defines the vector to transform
  2681. * @param transformation defines the matrix to apply
  2682. * @param result defines the target vector
  2683. */
  2684. Vector2.TransformToRef = function (vector, transformation, result) {
  2685. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2686. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2687. result.x = x;
  2688. result.y = y;
  2689. };
  2690. /**
  2691. * Determines if a given vector is included in a triangle
  2692. * @param p defines the vector to test
  2693. * @param p0 defines 1st triangle point
  2694. * @param p1 defines 2nd triangle point
  2695. * @param p2 defines 3rd triangle point
  2696. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2697. */
  2698. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2699. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2700. var sign = a < 0 ? -1 : 1;
  2701. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2702. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2703. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2704. };
  2705. /**
  2706. * Gets the distance between the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns the distance between vectors
  2710. */
  2711. Vector2.Distance = function (value1, value2) {
  2712. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2713. };
  2714. /**
  2715. * Returns the squared distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the squared distance between vectors
  2719. */
  2720. Vector2.DistanceSquared = function (value1, value2) {
  2721. var x = value1.x - value2.x;
  2722. var y = value1.y - value2.y;
  2723. return (x * x) + (y * y);
  2724. };
  2725. /**
  2726. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2727. * @param value1 defines first vector
  2728. * @param value2 defines second vector
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Center = function (value1, value2) {
  2732. var center = value1.add(value2);
  2733. center.scaleInPlace(0.5);
  2734. return center;
  2735. };
  2736. /**
  2737. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2738. * @param p defines the middle point
  2739. * @param segA defines one point of the segment
  2740. * @param segB defines the other point of the segment
  2741. * @returns the shortest distance
  2742. */
  2743. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2744. var l2 = Vector2.DistanceSquared(segA, segB);
  2745. if (l2 === 0.0) {
  2746. return Vector2.Distance(p, segA);
  2747. }
  2748. var v = segB.subtract(segA);
  2749. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2750. var proj = segA.add(v.multiplyByFloats(t, t));
  2751. return Vector2.Distance(p, proj);
  2752. };
  2753. return Vector2;
  2754. }());
  2755. BABYLON.Vector2 = Vector2;
  2756. /**
  2757. * Classed used to store (x,y,z) vector representation
  2758. * A Vector3 is the main object used in 3D geometry
  2759. * It can represent etiher the coordinates of a point the space, either a direction
  2760. * Reminder: Babylon.js uses a left handed forward facing system
  2761. */
  2762. var Vector3 = /** @class */ (function () {
  2763. /**
  2764. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2765. * @param x defines the first coordinates (on X axis)
  2766. * @param y defines the second coordinates (on Y axis)
  2767. * @param z defines the third coordinates (on Z axis)
  2768. */
  2769. function Vector3(
  2770. /**
  2771. * Defines the first coordinates (on X axis)
  2772. */
  2773. x,
  2774. /**
  2775. * Defines the second coordinates (on Y axis)
  2776. */
  2777. y,
  2778. /**
  2779. * Defines the third coordinates (on Z axis)
  2780. */
  2781. z) {
  2782. this.x = x;
  2783. this.y = y;
  2784. this.z = z;
  2785. }
  2786. /**
  2787. * Creates a string representation of the Vector3
  2788. * @returns a string with the Vector3 coordinates.
  2789. */
  2790. Vector3.prototype.toString = function () {
  2791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2792. };
  2793. /**
  2794. * Gets the class name
  2795. * @returns the string "Vector3"
  2796. */
  2797. Vector3.prototype.getClassName = function () {
  2798. return "Vector3";
  2799. };
  2800. /**
  2801. * Creates the Vector3 hash code
  2802. * @returns a number which tends to be unique between Vector3 instances
  2803. */
  2804. Vector3.prototype.getHashCode = function () {
  2805. var hash = this.x || 0;
  2806. hash = (hash * 397) ^ (this.y || 0);
  2807. hash = (hash * 397) ^ (this.z || 0);
  2808. return hash;
  2809. };
  2810. // Operators
  2811. /**
  2812. * Creates an array containing three elements : the coordinates of the Vector3
  2813. * @returns a new array of numbers
  2814. */
  2815. Vector3.prototype.asArray = function () {
  2816. var result = [];
  2817. this.toArray(result, 0);
  2818. return result;
  2819. };
  2820. /**
  2821. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2822. * @param array defines the destination array
  2823. * @param index defines the offset in the destination array
  2824. * @returns the current Vector3
  2825. */
  2826. Vector3.prototype.toArray = function (array, index) {
  2827. if (index === void 0) { index = 0; }
  2828. array[index] = this.x;
  2829. array[index + 1] = this.y;
  2830. array[index + 2] = this.z;
  2831. return this;
  2832. };
  2833. /**
  2834. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2835. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2836. */
  2837. Vector3.prototype.toQuaternion = function () {
  2838. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2839. };
  2840. /**
  2841. * Adds the given vector to the current Vector3
  2842. * @param otherVector defines the second operand
  2843. * @returns the current updated Vector3
  2844. */
  2845. Vector3.prototype.addInPlace = function (otherVector) {
  2846. this.x += otherVector.x;
  2847. this.y += otherVector.y;
  2848. this.z += otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2853. * @param otherVector defines the second operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.add = function (otherVector) {
  2857. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2858. };
  2859. /**
  2860. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2861. * @param otherVector defines the second operand
  2862. * @param result defines the Vector3 object where to store the result
  2863. * @returns the current Vector3
  2864. */
  2865. Vector3.prototype.addToRef = function (otherVector, result) {
  2866. result.x = this.x + otherVector.x;
  2867. result.y = this.y + otherVector.y;
  2868. result.z = this.z + otherVector.z;
  2869. return this;
  2870. };
  2871. /**
  2872. * Subtract the given vector from the current Vector3
  2873. * @param otherVector defines the second operand
  2874. * @returns the current updated Vector3
  2875. */
  2876. Vector3.prototype.subtractInPlace = function (otherVector) {
  2877. this.x -= otherVector.x;
  2878. this.y -= otherVector.y;
  2879. this.z -= otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2884. * @param otherVector defines the second operand
  2885. * @returns the resulting Vector3
  2886. */
  2887. Vector3.prototype.subtract = function (otherVector) {
  2888. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2889. };
  2890. /**
  2891. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2892. * @param otherVector defines the second operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2897. result.x = this.x - otherVector.x;
  2898. result.y = this.y - otherVector.y;
  2899. result.z = this.z - otherVector.z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2904. * @param x defines the x coordinate of the operand
  2905. * @param y defines the y coordinate of the operand
  2906. * @param z defines the z coordinate of the operand
  2907. * @returns the resulting Vector3
  2908. */
  2909. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2910. return new Vector3(this.x - x, this.y - y, this.z - z);
  2911. };
  2912. /**
  2913. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2914. * @param x defines the x coordinate of the operand
  2915. * @param y defines the y coordinate of the operand
  2916. * @param z defines the z coordinate of the operand
  2917. * @param result defines the Vector3 object where to store the result
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2921. result.x = this.x - x;
  2922. result.y = this.y - y;
  2923. result.z = this.z - z;
  2924. return this;
  2925. };
  2926. /**
  2927. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2928. * @returns a new Vector3
  2929. */
  2930. Vector3.prototype.negate = function () {
  2931. return new Vector3(-this.x, -this.y, -this.z);
  2932. };
  2933. /**
  2934. * Multiplies the Vector3 coordinates by the float "scale"
  2935. * @param scale defines the multiplier factor
  2936. * @returns the current updated Vector3
  2937. */
  2938. Vector3.prototype.scaleInPlace = function (scale) {
  2939. this.x *= scale;
  2940. this.y *= scale;
  2941. this.z *= scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2946. * @param scale defines the multiplier factor
  2947. * @returns a new Vector3
  2948. */
  2949. Vector3.prototype.scale = function (scale) {
  2950. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2951. };
  2952. /**
  2953. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2954. * @param scale defines the multiplier factor
  2955. * @param result defines the Vector3 object where to store the result
  2956. * @returns the current Vector3
  2957. */
  2958. Vector3.prototype.scaleToRef = function (scale, result) {
  2959. result.x = this.x * scale;
  2960. result.y = this.y * scale;
  2961. result.z = this.z * scale;
  2962. return this;
  2963. };
  2964. /**
  2965. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2966. * @param scale defines the scale factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the unmodified current Vector3
  2969. */
  2970. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2971. result.x += this.x * scale;
  2972. result.y += this.y * scale;
  2973. result.z += this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2978. * @param otherVector defines the second operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equals = function (otherVector) {
  2982. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2983. };
  2984. /**
  2985. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2986. * @param otherVector defines the second operand
  2987. * @param epsilon defines the minimal distance to define values as equals
  2988. * @returns true if both vectors are distant less than epsilon
  2989. */
  2990. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2991. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2992. 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);
  2993. };
  2994. /**
  2995. * Returns true if the current Vector3 coordinates equals the given floats
  2996. * @param x defines the x coordinate of the operand
  2997. * @param y defines the y coordinate of the operand
  2998. * @param z defines the z coordinate of the operand
  2999. * @returns true if both vectors are equals
  3000. */
  3001. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3002. return this.x === x && this.y === y && this.z === z;
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the given ones
  3006. * @param otherVector defines the second operand
  3007. * @returns the current updated Vector3
  3008. */
  3009. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3010. this.x *= otherVector.x;
  3011. this.y *= otherVector.y;
  3012. this.z *= otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3017. * @param otherVector defines the second operand
  3018. * @returns the new Vector3
  3019. */
  3020. Vector3.prototype.multiply = function (otherVector) {
  3021. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3022. };
  3023. /**
  3024. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3025. * @param otherVector defines the second operand
  3026. * @param result defines the Vector3 object where to store the result
  3027. * @returns the current Vector3
  3028. */
  3029. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3030. result.x = this.x * otherVector.x;
  3031. result.y = this.y * otherVector.y;
  3032. result.z = this.z * otherVector.z;
  3033. return this;
  3034. };
  3035. /**
  3036. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3037. * @param x defines the x coordinate of the operand
  3038. * @param y defines the y coordinate of the operand
  3039. * @param z defines the z coordinate of the operand
  3040. * @returns the new Vector3
  3041. */
  3042. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3043. return new Vector3(this.x * x, this.y * y, this.z * z);
  3044. };
  3045. /**
  3046. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3047. * @param otherVector defines the second operand
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.divide = function (otherVector) {
  3051. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3052. };
  3053. /**
  3054. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3055. * @param otherVector defines the second operand
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the current Vector3
  3058. */
  3059. Vector3.prototype.divideToRef = function (otherVector, result) {
  3060. result.x = this.x / otherVector.x;
  3061. result.y = this.y / otherVector.y;
  3062. result.z = this.z / otherVector.z;
  3063. return this;
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones.
  3067. * @param otherVector defines the second operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.divideInPlace = function (otherVector) {
  3071. return this.divideToRef(otherVector, this);
  3072. };
  3073. /**
  3074. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3075. * @param other defines the second operand
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.minimizeInPlace = function (other) {
  3079. if (other.x < this.x)
  3080. this.x = other.x;
  3081. if (other.y < this.y)
  3082. this.y = other.y;
  3083. if (other.z < this.z)
  3084. this.z = other.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3089. * @param other defines the second operand
  3090. * @returns the current updated Vector3
  3091. */
  3092. Vector3.prototype.maximizeInPlace = function (other) {
  3093. if (other.x > this.x)
  3094. this.x = other.x;
  3095. if (other.y > this.y)
  3096. this.y = other.y;
  3097. if (other.z > this.z)
  3098. this.z = other.z;
  3099. return this;
  3100. };
  3101. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3102. /**
  3103. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3104. */
  3105. get: function () {
  3106. var absX = Math.abs(this.x);
  3107. var absY = Math.abs(this.y);
  3108. if (absX !== absY) {
  3109. return true;
  3110. }
  3111. var absZ = Math.abs(this.z);
  3112. if (absX !== absZ) {
  3113. return true;
  3114. }
  3115. if (absY !== absZ) {
  3116. return true;
  3117. }
  3118. return false;
  3119. },
  3120. enumerable: true,
  3121. configurable: true
  3122. });
  3123. // Properties
  3124. /**
  3125. * Gets the length of the Vector3
  3126. * @returns the length of the Vecto3
  3127. */
  3128. Vector3.prototype.length = function () {
  3129. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3130. };
  3131. /**
  3132. * Gets the squared length of the Vector3
  3133. * @returns squared length of the Vector3
  3134. */
  3135. Vector3.prototype.lengthSquared = function () {
  3136. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Normalize the current Vector3.
  3140. * Please note that this is an in place operation.
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.normalize = function () {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0)
  3146. return this;
  3147. var num = 1.0 / len;
  3148. this.x *= num;
  3149. this.y *= num;
  3150. this.z *= num;
  3151. return this;
  3152. };
  3153. /**
  3154. * Normalize the current Vector3 to a new vector
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.normalizeToNew = function () {
  3158. var normalized = new Vector3(0, 0, 0);
  3159. this.normalizeToRef(normalized);
  3160. return normalized;
  3161. };
  3162. /**
  3163. * Normalize the current Vector3 to the reference
  3164. * @param reference define the Vector3 to update
  3165. * @returns the updated Vector3
  3166. */
  3167. Vector3.prototype.normalizeToRef = function (reference) {
  3168. var len = this.length();
  3169. if (len === 0 || len === 1.0) {
  3170. reference.set(this.x, this.y, this.z);
  3171. return reference;
  3172. }
  3173. var scale = 1.0 / len;
  3174. this.scaleToRef(scale, reference);
  3175. return reference;
  3176. };
  3177. /**
  3178. * Creates a new Vector3 copied from the current Vector3
  3179. * @returns the new Vector3
  3180. */
  3181. Vector3.prototype.clone = function () {
  3182. return new Vector3(this.x, this.y, this.z);
  3183. };
  3184. /**
  3185. * Copies the given vector coordinates to the current Vector3 ones
  3186. * @param source defines the source Vector3
  3187. * @returns the current updated Vector3
  3188. */
  3189. Vector3.prototype.copyFrom = function (source) {
  3190. this.x = source.x;
  3191. this.y = source.y;
  3192. this.z = source.z;
  3193. return this;
  3194. };
  3195. /**
  3196. * Copies the given floats to the current Vector3 coordinates
  3197. * @param x defines the x coordinate of the operand
  3198. * @param y defines the y coordinate of the operand
  3199. * @param z defines the z coordinate of the operand
  3200. * @returns the current updated Vector3
  3201. */
  3202. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3203. this.x = x;
  3204. this.y = y;
  3205. this.z = z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Copies the given floats to the current Vector3 coordinates
  3210. * @param x defines the x coordinate of the operand
  3211. * @param y defines the y coordinate of the operand
  3212. * @param z defines the z coordinate of the operand
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.set = function (x, y, z) {
  3216. return this.copyFromFloats(x, y, z);
  3217. };
  3218. // Statics
  3219. /**
  3220. * Get the clip factor between two vectors
  3221. * @param vector0 defines the first operand
  3222. * @param vector1 defines the second operand
  3223. * @param axis defines the axis to use
  3224. * @param size defines the size along the axis
  3225. * @returns the clip factor
  3226. */
  3227. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3228. var d0 = Vector3.Dot(vector0, axis) - size;
  3229. var d1 = Vector3.Dot(vector1, axis) - size;
  3230. var s = d0 / (d0 - d1);
  3231. return s;
  3232. };
  3233. /**
  3234. * Get angle between two vectors
  3235. * @param vector0 angle between vector0 and vector1
  3236. * @param vector1 angle between vector0 and vector1
  3237. * @param normal direction of the normal
  3238. * @return the angle between vector0 and vector1
  3239. */
  3240. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3241. var v0 = vector0.clone().normalize();
  3242. var v1 = vector1.clone().normalize();
  3243. var dot = Vector3.Dot(v0, v1);
  3244. var n = Vector3.Cross(v0, v1);
  3245. if (Vector3.Dot(n, normal) > 0) {
  3246. return Math.acos(dot);
  3247. }
  3248. return -Math.acos(dot);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set from the index "offset" of the given array
  3252. * @param array defines the source array
  3253. * @param offset defines the offset in the source array
  3254. * @returns the new Vector3
  3255. */
  3256. Vector3.FromArray = function (array, offset) {
  3257. if (!offset) {
  3258. offset = 0;
  3259. }
  3260. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3264. * This function is deprecated. Use FromArray instead
  3265. * @param array defines the source array
  3266. * @param offset defines the offset in the source array
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.FromFloatArray = function (array, offset) {
  3270. return Vector3.FromArray(array, offset);
  3271. };
  3272. /**
  3273. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3274. * @param array defines the source array
  3275. * @param offset defines the offset in the source array
  3276. * @param result defines the Vector3 where to store the result
  3277. */
  3278. Vector3.FromArrayToRef = function (array, offset, result) {
  3279. result.x = array[offset];
  3280. result.y = array[offset + 1];
  3281. result.z = array[offset + 2];
  3282. };
  3283. /**
  3284. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3285. * This function is deprecated. Use FromArrayToRef instead.
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3291. return Vector3.FromArrayToRef(array, offset, result);
  3292. };
  3293. /**
  3294. * Sets the given vector "result" with the given floats.
  3295. * @param x defines the x coordinate of the source
  3296. * @param y defines the y coordinate of the source
  3297. * @param z defines the z coordinate of the source
  3298. * @param result defines the Vector3 where to store the result
  3299. */
  3300. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. };
  3305. /**
  3306. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3307. * @returns a new empty Vector3
  3308. */
  3309. Vector3.Zero = function () {
  3310. return new Vector3(0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3314. * @returns a new unit Vector3
  3315. */
  3316. Vector3.One = function () {
  3317. return new Vector3(1.0, 1.0, 1.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3321. * @returns a new up Vector3
  3322. */
  3323. Vector3.Up = function () {
  3324. return new Vector3(0.0, 1.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3328. * @returns a new forward Vector3
  3329. */
  3330. Vector3.Forward = function () {
  3331. return new Vector3(0.0, 0.0, 1.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3335. * @returns a new right Vector3
  3336. */
  3337. Vector3.Right = function () {
  3338. return new Vector3(1.0, 0.0, 0.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3342. * @returns a new left Vector3
  3343. */
  3344. Vector3.Left = function () {
  3345. return new Vector3(-1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3349. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3350. * @param vector defines the Vector3 to transform
  3351. * @param transformation defines the transformation matrix
  3352. * @returns the transformed Vector3
  3353. */
  3354. Vector3.TransformCoordinates = function (vector, transformation) {
  3355. var result = Vector3.Zero();
  3356. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3357. return result;
  3358. };
  3359. /**
  3360. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3361. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3362. * @param vector defines the Vector3 to transform
  3363. * @param transformation defines the transformation matrix
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3367. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3368. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3369. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3370. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3371. result.x = x / w;
  3372. result.y = y / w;
  3373. result.z = z / w;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3377. * This method computes tranformed coordinates only, not transformed direction vectors
  3378. * @param x define the x coordinate of the source vector
  3379. * @param y define the y coordinate of the source vector
  3380. * @param z define the z coordinate of the source vector
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3385. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3386. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3387. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3388. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3389. result.x = rx / rw;
  3390. result.y = ry / rw;
  3391. result.z = rz / rw;
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the new Vector3
  3399. */
  3400. Vector3.TransformNormal = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformNormalToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3407. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3416. result.x = x;
  3417. result.y = y;
  3418. result.z = z;
  3419. };
  3420. /**
  3421. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3422. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3423. * @param x define the x coordinate of the source vector
  3424. * @param y define the y coordinate of the source vector
  3425. * @param z define the z coordinate of the source vector
  3426. * @param transformation defines the transformation matrix
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3430. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3431. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3432. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3436. * @param value1 defines the first control point
  3437. * @param value2 defines the second control point
  3438. * @param value3 defines the third control point
  3439. * @param value4 defines the fourth control point
  3440. * @param amount defines the amount on the spline to use
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3444. var squared = amount * amount;
  3445. var cubed = amount * squared;
  3446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3452. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3453. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3454. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3455. return new Vector3(x, y, z);
  3456. };
  3457. /**
  3458. * 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"
  3459. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3460. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3461. * @param value defines the current value
  3462. * @param min defines the lower range value
  3463. * @param max defines the upper range value
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Clamp = function (value, min, max) {
  3467. var x = value.x;
  3468. x = (x > max.x) ? max.x : x;
  3469. x = (x < min.x) ? min.x : x;
  3470. var y = value.y;
  3471. y = (y > max.y) ? max.y : y;
  3472. y = (y < min.y) ? min.y : y;
  3473. var z = value.z;
  3474. z = (z > max.z) ? max.z : z;
  3475. z = (z < min.z) ? min.z : z;
  3476. return new Vector3(x, y, z);
  3477. };
  3478. /**
  3479. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3480. * @param value1 defines the first control point
  3481. * @param tangent1 defines the first tangent vector
  3482. * @param value2 defines the second control point
  3483. * @param tangent2 defines the second tangent vector
  3484. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3485. * @returns the new Vector3
  3486. */
  3487. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3488. var squared = amount * amount;
  3489. var cubed = amount * squared;
  3490. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3491. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3492. var part3 = (cubed - (2.0 * squared)) + amount;
  3493. var part4 = cubed - squared;
  3494. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3495. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3496. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3497. return new Vector3(x, y, z);
  3498. };
  3499. /**
  3500. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3501. * @param start defines the start value
  3502. * @param end defines the end value
  3503. * @param amount max defines amount between both (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Lerp = function (start, end, amount) {
  3507. var result = new Vector3(0, 0, 0);
  3508. Vector3.LerpToRef(start, end, amount, result);
  3509. return result;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3513. * @param start defines the start value
  3514. * @param end defines the end value
  3515. * @param amount max defines amount between both (between 0 and 1)
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.LerpToRef = function (start, end, amount, result) {
  3519. result.x = start.x + ((end.x - start.x) * amount);
  3520. result.y = start.y + ((end.y - start.y) * amount);
  3521. result.z = start.z + ((end.z - start.z) * amount);
  3522. };
  3523. /**
  3524. * Returns the dot product (float) between the vectors "left" and "right"
  3525. * @param left defines the left operand
  3526. * @param right defines the right operand
  3527. * @returns the dot product
  3528. */
  3529. Vector3.Dot = function (left, right) {
  3530. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3531. };
  3532. /**
  3533. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3534. * The cross product is then orthogonal to both "left" and "right"
  3535. * @param left defines the left operand
  3536. * @param right defines the right operand
  3537. * @returns the cross product
  3538. */
  3539. Vector3.Cross = function (left, right) {
  3540. var result = Vector3.Zero();
  3541. Vector3.CrossToRef(left, right, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the given vector "result" with the cross product of "left" and "right"
  3546. * The cross product is then orthogonal to both "left" and "right"
  3547. * @param left defines the left operand
  3548. * @param right defines the right operand
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.CrossToRef = function (left, right, result) {
  3552. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3553. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3554. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3555. result.copyFrom(MathTmp.Vector3[0]);
  3556. };
  3557. /**
  3558. * Returns a new Vector3 as the normalization of the given vector
  3559. * @param vector defines the Vector3 to normalize
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Normalize = function (vector) {
  3563. var result = Vector3.Zero();
  3564. Vector3.NormalizeToRef(vector, result);
  3565. return result;
  3566. };
  3567. /**
  3568. * Sets the given vector "result" with the normalization of the given first vector
  3569. * @param vector defines the Vector3 to normalize
  3570. * @param result defines the Vector3 where to store the result
  3571. */
  3572. Vector3.NormalizeToRef = function (vector, result) {
  3573. result.copyFrom(vector);
  3574. result.normalize();
  3575. };
  3576. /**
  3577. * Project a Vector3 onto screen space
  3578. * @param vector defines the Vector3 to project
  3579. * @param world defines the world matrix to use
  3580. * @param transform defines the transform (view x projection) matrix to use
  3581. * @param viewport defines the screen viewport to use
  3582. * @returns the new Vector3
  3583. */
  3584. Vector3.Project = function (vector, world, transform, viewport) {
  3585. var cw = viewport.width;
  3586. var ch = viewport.height;
  3587. var cx = viewport.x;
  3588. var cy = viewport.y;
  3589. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3590. 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);
  3591. var matrix = MathTmp.Matrix[0];
  3592. world.multiplyToRef(transform, matrix);
  3593. matrix.multiplyToRef(viewportMatrix, matrix);
  3594. return Vector3.TransformCoordinates(vector, matrix);
  3595. };
  3596. /**
  3597. * Unproject from screen space to object space
  3598. * @param source defines the screen space Vector3 to use
  3599. * @param viewportWidth defines the current width of the viewport
  3600. * @param viewportHeight defines the current height of the viewport
  3601. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3602. * @param transform defines the transform (view x projection) matrix to use
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3606. var matrix = MathTmp.Matrix[0];
  3607. world.multiplyToRef(transform, matrix);
  3608. matrix.invert();
  3609. source.x = source.x / viewportWidth * 2 - 1;
  3610. source.y = -(source.y / viewportHeight * 2 - 1);
  3611. var vector = Vector3.TransformCoordinates(source, matrix);
  3612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3614. vector = vector.scale(1.0 / num);
  3615. }
  3616. return vector;
  3617. };
  3618. /**
  3619. * Unproject from screen space to object space
  3620. * @param source defines the screen space Vector3 to use
  3621. * @param viewportWidth defines the current width of the viewport
  3622. * @param viewportHeight defines the current height of the viewport
  3623. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3624. * @param view defines the view matrix to use
  3625. * @param projection defines the projection matrix to use
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3629. var result = Vector3.Zero();
  3630. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Unproject from screen space to object space
  3635. * @param source defines the screen space Vector3 to use
  3636. * @param viewportWidth defines the current width of the viewport
  3637. * @param viewportHeight defines the current height of the viewport
  3638. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3639. * @param view defines the view matrix to use
  3640. * @param projection defines the projection matrix to use
  3641. * @param result defines the Vector3 where to store the result
  3642. */
  3643. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3644. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3645. };
  3646. /**
  3647. * Unproject from screen space to object space
  3648. * @param sourceX defines the screen space x coordinate to use
  3649. * @param sourceY defines the screen space y coordinate to use
  3650. * @param sourceZ defines the screen space z coordinate to use
  3651. * @param viewportWidth defines the current width of the viewport
  3652. * @param viewportHeight defines the current height of the viewport
  3653. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3654. * @param view defines the view matrix to use
  3655. * @param projection defines the projection matrix to use
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3659. var matrix = MathTmp.Matrix[0];
  3660. world.multiplyToRef(view, matrix);
  3661. matrix.multiplyToRef(projection, matrix);
  3662. matrix.invert();
  3663. var screenSource = MathTmp.Vector3[0];
  3664. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3665. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3666. screenSource.z = 2 * sourceZ - 1.0;
  3667. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3668. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3669. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3670. result.scaleInPlace(1.0 / num);
  3671. }
  3672. };
  3673. /**
  3674. * Gets the minimal coordinate values between two Vector3
  3675. * @param left defines the first operand
  3676. * @param right defines the second operand
  3677. * @returns the new Vector3
  3678. */
  3679. Vector3.Minimize = function (left, right) {
  3680. var min = left.clone();
  3681. min.minimizeInPlace(right);
  3682. return min;
  3683. };
  3684. /**
  3685. * Gets the maximal coordinate values between two Vector3
  3686. * @param left defines the first operand
  3687. * @param right defines the second operand
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.Maximize = function (left, right) {
  3691. var max = left.clone();
  3692. max.maximizeInPlace(right);
  3693. return max;
  3694. };
  3695. /**
  3696. * Returns the distance between the vectors "value1" and "value2"
  3697. * @param value1 defines the first operand
  3698. * @param value2 defines the second operand
  3699. * @returns the distance
  3700. */
  3701. Vector3.Distance = function (value1, value2) {
  3702. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3703. };
  3704. /**
  3705. * Returns the squared distance between the vectors "value1" and "value2"
  3706. * @param value1 defines the first operand
  3707. * @param value2 defines the second operand
  3708. * @returns the squared distance
  3709. */
  3710. Vector3.DistanceSquared = function (value1, value2) {
  3711. var x = value1.x - value2.x;
  3712. var y = value1.y - value2.y;
  3713. var z = value1.z - value2.z;
  3714. return (x * x) + (y * y) + (z * z);
  3715. };
  3716. /**
  3717. * Returns a new Vector3 located at the center between "value1" and "value2"
  3718. * @param value1 defines the first operand
  3719. * @param value2 defines the second operand
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Center = function (value1, value2) {
  3723. var center = value1.add(value2);
  3724. center.scaleInPlace(0.5);
  3725. return center;
  3726. };
  3727. /**
  3728. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3729. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3730. * to something in order to rotate it from its local system to the given target system
  3731. * Note: axis1, axis2 and axis3 are normalized during this operation
  3732. * @param axis1 defines the first axis
  3733. * @param axis2 defines the second axis
  3734. * @param axis3 defines the third axis
  3735. * @returns a new Vector3
  3736. */
  3737. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3738. var rotation = Vector3.Zero();
  3739. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3740. return rotation;
  3741. };
  3742. /**
  3743. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3744. * @param axis1 defines the first axis
  3745. * @param axis2 defines the second axis
  3746. * @param axis3 defines the third axis
  3747. * @param ref defines the Vector3 where to store the result
  3748. */
  3749. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3750. var quat = MathTmp.Quaternion[0];
  3751. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3752. quat.toEulerAnglesToRef(ref);
  3753. };
  3754. return Vector3;
  3755. }());
  3756. BABYLON.Vector3 = Vector3;
  3757. //Vector4 class created for EulerAngle class conversion to Quaternion
  3758. var Vector4 = /** @class */ (function () {
  3759. /**
  3760. * Creates a Vector4 object from the given floats.
  3761. */
  3762. function Vector4(x, y, z, w) {
  3763. this.x = x;
  3764. this.y = y;
  3765. this.z = z;
  3766. this.w = w;
  3767. }
  3768. /**
  3769. * Returns the string with the Vector4 coordinates.
  3770. */
  3771. Vector4.prototype.toString = function () {
  3772. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3773. };
  3774. /**
  3775. * Returns the string "Vector4".
  3776. */
  3777. Vector4.prototype.getClassName = function () {
  3778. return "Vector4";
  3779. };
  3780. /**
  3781. * Returns the Vector4 hash code.
  3782. */
  3783. Vector4.prototype.getHashCode = function () {
  3784. var hash = this.x || 0;
  3785. hash = (hash * 397) ^ (this.y || 0);
  3786. hash = (hash * 397) ^ (this.z || 0);
  3787. hash = (hash * 397) ^ (this.w || 0);
  3788. return hash;
  3789. };
  3790. // Operators
  3791. /**
  3792. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3793. */
  3794. Vector4.prototype.asArray = function () {
  3795. var result = new Array();
  3796. this.toArray(result, 0);
  3797. return result;
  3798. };
  3799. /**
  3800. * Populates the given array from the given index with the Vector4 coordinates.
  3801. * Returns the Vector4.
  3802. */
  3803. Vector4.prototype.toArray = function (array, index) {
  3804. if (index === undefined) {
  3805. index = 0;
  3806. }
  3807. array[index] = this.x;
  3808. array[index + 1] = this.y;
  3809. array[index + 2] = this.z;
  3810. array[index + 3] = this.w;
  3811. return this;
  3812. };
  3813. /**
  3814. * Adds the given vector to the current Vector4.
  3815. * Returns the updated Vector4.
  3816. */
  3817. Vector4.prototype.addInPlace = function (otherVector) {
  3818. this.x += otherVector.x;
  3819. this.y += otherVector.y;
  3820. this.z += otherVector.z;
  3821. this.w += otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3826. */
  3827. Vector4.prototype.add = function (otherVector) {
  3828. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3829. };
  3830. /**
  3831. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.addToRef = function (otherVector, result) {
  3835. result.x = this.x + otherVector.x;
  3836. result.y = this.y + otherVector.y;
  3837. result.z = this.z + otherVector.z;
  3838. result.w = this.w + otherVector.w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Subtract in place the given vector from the current Vector4.
  3843. * Returns the updated Vector4.
  3844. */
  3845. Vector4.prototype.subtractInPlace = function (otherVector) {
  3846. this.x -= otherVector.x;
  3847. this.y -= otherVector.y;
  3848. this.z -= otherVector.z;
  3849. this.w -= otherVector.w;
  3850. return this;
  3851. };
  3852. /**
  3853. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3854. */
  3855. Vector4.prototype.subtract = function (otherVector) {
  3856. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3857. };
  3858. /**
  3859. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3860. * Returns the current Vector4.
  3861. */
  3862. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3863. result.x = this.x - otherVector.x;
  3864. result.y = this.y - otherVector.y;
  3865. result.z = this.z - otherVector.z;
  3866. result.w = this.w - otherVector.w;
  3867. return this;
  3868. };
  3869. /**
  3870. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3873. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3874. };
  3875. /**
  3876. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3877. * Returns the current Vector4.
  3878. */
  3879. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3880. result.x = this.x - x;
  3881. result.y = this.y - y;
  3882. result.z = this.z - z;
  3883. result.w = this.w - w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3888. */
  3889. Vector4.prototype.negate = function () {
  3890. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3891. };
  3892. /**
  3893. * Multiplies the current Vector4 coordinates by scale (float).
  3894. * Returns the updated Vector4.
  3895. */
  3896. Vector4.prototype.scaleInPlace = function (scale) {
  3897. this.x *= scale;
  3898. this.y *= scale;
  3899. this.z *= scale;
  3900. this.w *= scale;
  3901. return this;
  3902. };
  3903. /**
  3904. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3905. */
  3906. Vector4.prototype.scale = function (scale) {
  3907. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3908. };
  3909. /**
  3910. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3911. * Returns the current Vector4.
  3912. */
  3913. Vector4.prototype.scaleToRef = function (scale, result) {
  3914. result.x = this.x * scale;
  3915. result.y = this.y * scale;
  3916. result.z = this.z * scale;
  3917. result.w = this.w * scale;
  3918. return this;
  3919. };
  3920. /**
  3921. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3922. * @param scale defines the scale factor
  3923. * @param result defines the Vector4 object where to store the result
  3924. * @returns the unmodified current Vector4
  3925. */
  3926. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3927. result.x += this.x * scale;
  3928. result.y += this.y * scale;
  3929. result.z += this.z * scale;
  3930. result.w += this.w * scale;
  3931. return this;
  3932. };
  3933. /**
  3934. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3935. */
  3936. Vector4.prototype.equals = function (otherVector) {
  3937. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3938. };
  3939. /**
  3940. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3941. */
  3942. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3943. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3944. return otherVector
  3945. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3946. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3947. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3948. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3949. };
  3950. /**
  3951. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3952. */
  3953. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3954. return this.x === x && this.y === y && this.z === z && this.w === w;
  3955. };
  3956. /**
  3957. * Multiplies in place the current Vector4 by the given one.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3961. this.x *= otherVector.x;
  3962. this.y *= otherVector.y;
  3963. this.z *= otherVector.z;
  3964. this.w *= otherVector.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3969. */
  3970. Vector4.prototype.multiply = function (otherVector) {
  3971. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3972. };
  3973. /**
  3974. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3975. * Returns the current Vector4.
  3976. */
  3977. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3978. result.x = this.x * otherVector.x;
  3979. result.y = this.y * otherVector.y;
  3980. result.z = this.z * otherVector.z;
  3981. result.w = this.w * otherVector.w;
  3982. return this;
  3983. };
  3984. /**
  3985. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3986. */
  3987. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3988. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3989. };
  3990. /**
  3991. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3992. */
  3993. Vector4.prototype.divide = function (otherVector) {
  3994. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3995. };
  3996. /**
  3997. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3998. * Returns the current Vector4.
  3999. */
  4000. Vector4.prototype.divideToRef = function (otherVector, result) {
  4001. result.x = this.x / otherVector.x;
  4002. result.y = this.y / otherVector.y;
  4003. result.z = this.z / otherVector.z;
  4004. result.w = this.w / otherVector.w;
  4005. return this;
  4006. };
  4007. /**
  4008. * Divides the current Vector3 coordinates by the given ones.
  4009. * @returns the updated Vector3.
  4010. */
  4011. Vector4.prototype.divideInPlace = function (otherVector) {
  4012. return this.divideToRef(otherVector, this);
  4013. };
  4014. /**
  4015. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4016. * @param other defines the second operand
  4017. * @returns the current updated Vector4
  4018. */
  4019. Vector4.prototype.minimizeInPlace = function (other) {
  4020. if (other.x < this.x)
  4021. this.x = other.x;
  4022. if (other.y < this.y)
  4023. this.y = other.y;
  4024. if (other.z < this.z)
  4025. this.z = other.z;
  4026. if (other.w < this.w)
  4027. this.w = other.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4032. * @param other defines the second operand
  4033. * @returns the current updated Vector4
  4034. */
  4035. Vector4.prototype.maximizeInPlace = function (other) {
  4036. if (other.x > this.x)
  4037. this.x = other.x;
  4038. if (other.y > this.y)
  4039. this.y = other.y;
  4040. if (other.z > this.z)
  4041. this.z = other.z;
  4042. if (other.w > this.w)
  4043. this.w = other.w;
  4044. return this;
  4045. };
  4046. // Properties
  4047. /**
  4048. * Returns the Vector4 length (float).
  4049. */
  4050. Vector4.prototype.length = function () {
  4051. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4052. };
  4053. /**
  4054. * Returns the Vector4 squared length (float).
  4055. */
  4056. Vector4.prototype.lengthSquared = function () {
  4057. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4058. };
  4059. // Methods
  4060. /**
  4061. * Normalizes in place the Vector4.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.normalize = function () {
  4065. var len = this.length();
  4066. if (len === 0)
  4067. return this;
  4068. var num = 1.0 / len;
  4069. this.x *= num;
  4070. this.y *= num;
  4071. this.z *= num;
  4072. this.w *= num;
  4073. return this;
  4074. };
  4075. /**
  4076. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4077. */
  4078. Vector4.prototype.toVector3 = function () {
  4079. return new Vector3(this.x, this.y, this.z);
  4080. };
  4081. /**
  4082. * Returns a new Vector4 copied from the current one.
  4083. */
  4084. Vector4.prototype.clone = function () {
  4085. return new Vector4(this.x, this.y, this.z, this.w);
  4086. };
  4087. /**
  4088. * Updates the current Vector4 with the given one coordinates.
  4089. * Returns the updated Vector4.
  4090. */
  4091. Vector4.prototype.copyFrom = function (source) {
  4092. this.x = source.x;
  4093. this.y = source.y;
  4094. this.z = source.z;
  4095. this.w = source.w;
  4096. return this;
  4097. };
  4098. /**
  4099. * Updates the current Vector4 coordinates with the given floats.
  4100. * Returns the updated Vector4.
  4101. */
  4102. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4103. this.x = x;
  4104. this.y = y;
  4105. this.z = z;
  4106. this.w = w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Updates the current Vector4 coordinates with the given floats.
  4111. * Returns the updated Vector4.
  4112. */
  4113. Vector4.prototype.set = function (x, y, z, w) {
  4114. return this.copyFromFloats(x, y, z, w);
  4115. };
  4116. // Statics
  4117. /**
  4118. * Returns a new Vector4 set from the starting index of the given array.
  4119. */
  4120. Vector4.FromArray = function (array, offset) {
  4121. if (!offset) {
  4122. offset = 0;
  4123. }
  4124. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4125. };
  4126. /**
  4127. * Updates the given vector "result" from the starting index of the given array.
  4128. */
  4129. Vector4.FromArrayToRef = function (array, offset, result) {
  4130. result.x = array[offset];
  4131. result.y = array[offset + 1];
  4132. result.z = array[offset + 2];
  4133. result.w = array[offset + 3];
  4134. };
  4135. /**
  4136. * Updates the given vector "result" from the starting index of the given Float32Array.
  4137. */
  4138. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4139. Vector4.FromArrayToRef(array, offset, result);
  4140. };
  4141. /**
  4142. * Updates the given vector "result" coordinates from the given floats.
  4143. */
  4144. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4145. result.x = x;
  4146. result.y = y;
  4147. result.z = z;
  4148. result.w = w;
  4149. };
  4150. /**
  4151. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4152. */
  4153. Vector4.Zero = function () {
  4154. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4155. };
  4156. /**
  4157. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4158. */
  4159. Vector4.One = function () {
  4160. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4161. };
  4162. /**
  4163. * Returns a new normalized Vector4 from the given one.
  4164. */
  4165. Vector4.Normalize = function (vector) {
  4166. var result = Vector4.Zero();
  4167. Vector4.NormalizeToRef(vector, result);
  4168. return result;
  4169. };
  4170. /**
  4171. * Updates the given vector "result" from the normalization of the given one.
  4172. */
  4173. Vector4.NormalizeToRef = function (vector, result) {
  4174. result.copyFrom(vector);
  4175. result.normalize();
  4176. };
  4177. Vector4.Minimize = function (left, right) {
  4178. var min = left.clone();
  4179. min.minimizeInPlace(right);
  4180. return min;
  4181. };
  4182. Vector4.Maximize = function (left, right) {
  4183. var max = left.clone();
  4184. max.maximizeInPlace(right);
  4185. return max;
  4186. };
  4187. /**
  4188. * Returns the distance (float) between the vectors "value1" and "value2".
  4189. */
  4190. Vector4.Distance = function (value1, value2) {
  4191. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4192. };
  4193. /**
  4194. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4195. */
  4196. Vector4.DistanceSquared = function (value1, value2) {
  4197. var x = value1.x - value2.x;
  4198. var y = value1.y - value2.y;
  4199. var z = value1.z - value2.z;
  4200. var w = value1.w - value2.w;
  4201. return (x * x) + (y * y) + (z * z) + (w * w);
  4202. };
  4203. /**
  4204. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4205. */
  4206. Vector4.Center = function (value1, value2) {
  4207. var center = value1.add(value2);
  4208. center.scaleInPlace(0.5);
  4209. return center;
  4210. };
  4211. /**
  4212. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4213. * This methods computes transformed normalized direction vectors only.
  4214. */
  4215. Vector4.TransformNormal = function (vector, transformation) {
  4216. var result = Vector4.Zero();
  4217. Vector4.TransformNormalToRef(vector, transformation, result);
  4218. return result;
  4219. };
  4220. /**
  4221. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4222. * This methods computes transformed normalized direction vectors only.
  4223. */
  4224. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4228. result.x = x;
  4229. result.y = y;
  4230. result.z = z;
  4231. result.w = vector.w;
  4232. };
  4233. /**
  4234. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4235. * This methods computes transformed normalized direction vectors only.
  4236. */
  4237. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4238. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4239. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4240. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4241. result.w = w;
  4242. };
  4243. return Vector4;
  4244. }());
  4245. BABYLON.Vector4 = Vector4;
  4246. var Size = /** @class */ (function () {
  4247. /**
  4248. * Creates a Size object from the given width and height (floats).
  4249. */
  4250. function Size(width, height) {
  4251. this.width = width;
  4252. this.height = height;
  4253. }
  4254. // Returns a string with the Size width and height.
  4255. Size.prototype.toString = function () {
  4256. return "{W: " + this.width + ", H: " + this.height + "}";
  4257. };
  4258. /**
  4259. * Returns the string "Size"
  4260. */
  4261. Size.prototype.getClassName = function () {
  4262. return "Size";
  4263. };
  4264. /**
  4265. * Returns the Size hash code.
  4266. */
  4267. Size.prototype.getHashCode = function () {
  4268. var hash = this.width || 0;
  4269. hash = (hash * 397) ^ (this.height || 0);
  4270. return hash;
  4271. };
  4272. /**
  4273. * Updates the current size from the given one.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFrom = function (src) {
  4277. this.width = src.width;
  4278. this.height = src.height;
  4279. };
  4280. /**
  4281. * Updates in place the current Size from the given floats.
  4282. * Returns the updated Size.
  4283. */
  4284. Size.prototype.copyFromFloats = function (width, height) {
  4285. this.width = width;
  4286. this.height = height;
  4287. return this;
  4288. };
  4289. /**
  4290. * Updates in place the current Size from the given floats.
  4291. * Returns the updated Size.
  4292. */
  4293. Size.prototype.set = function (width, height) {
  4294. return this.copyFromFloats(width, height);
  4295. };
  4296. /**
  4297. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4298. */
  4299. Size.prototype.multiplyByFloats = function (w, h) {
  4300. return new Size(this.width * w, this.height * h);
  4301. };
  4302. /**
  4303. * Returns a new Size copied from the given one.
  4304. */
  4305. Size.prototype.clone = function () {
  4306. return new Size(this.width, this.height);
  4307. };
  4308. /**
  4309. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4310. */
  4311. Size.prototype.equals = function (other) {
  4312. if (!other) {
  4313. return false;
  4314. }
  4315. return (this.width === other.width) && (this.height === other.height);
  4316. };
  4317. Object.defineProperty(Size.prototype, "surface", {
  4318. /**
  4319. * Returns the surface of the Size : width * height (float).
  4320. */
  4321. get: function () {
  4322. return this.width * this.height;
  4323. },
  4324. enumerable: true,
  4325. configurable: true
  4326. });
  4327. /**
  4328. * Returns a new Size set to (0.0, 0.0)
  4329. */
  4330. Size.Zero = function () {
  4331. return new Size(0.0, 0.0);
  4332. };
  4333. /**
  4334. * Returns a new Size set as the addition result of the current Size and the given one.
  4335. */
  4336. Size.prototype.add = function (otherSize) {
  4337. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4338. return r;
  4339. };
  4340. /**
  4341. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4342. */
  4343. Size.prototype.subtract = function (otherSize) {
  4344. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4345. return r;
  4346. };
  4347. /**
  4348. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4349. */
  4350. Size.Lerp = function (start, end, amount) {
  4351. var w = start.width + ((end.width - start.width) * amount);
  4352. var h = start.height + ((end.height - start.height) * amount);
  4353. return new Size(w, h);
  4354. };
  4355. return Size;
  4356. }());
  4357. BABYLON.Size = Size;
  4358. /**
  4359. * Class used to store quaternion data
  4360. * @see https://en.wikipedia.org/wiki/Quaternion
  4361. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4362. */
  4363. var Quaternion = /** @class */ (function () {
  4364. /**
  4365. * Creates a new Quaternion from the given floats
  4366. * @param x defines the first component (0 by default)
  4367. * @param y defines the second component (0 by default)
  4368. * @param z defines the third component (0 by default)
  4369. * @param w defines the fourth component (1.0 by default)
  4370. */
  4371. function Quaternion(
  4372. /** defines the first component (0 by default) */
  4373. x,
  4374. /** defines the second component (0 by default) */
  4375. y,
  4376. /** defines the third component (0 by default) */
  4377. z,
  4378. /** defines the fourth component (1.0 by default) */
  4379. w) {
  4380. if (x === void 0) { x = 0.0; }
  4381. if (y === void 0) { y = 0.0; }
  4382. if (z === void 0) { z = 0.0; }
  4383. if (w === void 0) { w = 1.0; }
  4384. this.x = x;
  4385. this.y = y;
  4386. this.z = z;
  4387. this.w = w;
  4388. }
  4389. /**
  4390. * Gets a string representation for the current quaternion
  4391. * @returns a string with the Quaternion coordinates
  4392. */
  4393. Quaternion.prototype.toString = function () {
  4394. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4395. };
  4396. /**
  4397. * Gets the class name of the quaternion
  4398. * @returns the string "Quaternion"
  4399. */
  4400. Quaternion.prototype.getClassName = function () {
  4401. return "Quaternion";
  4402. };
  4403. /**
  4404. * Gets a hash code for this quaternion
  4405. * @returns the quaternion hash code
  4406. */
  4407. Quaternion.prototype.getHashCode = function () {
  4408. var hash = this.x || 0;
  4409. hash = (hash * 397) ^ (this.y || 0);
  4410. hash = (hash * 397) ^ (this.z || 0);
  4411. hash = (hash * 397) ^ (this.w || 0);
  4412. return hash;
  4413. };
  4414. /**
  4415. * Copy the quaternion to an array
  4416. * @returns a new array populated with 4 elements from the quaternion coordinates
  4417. */
  4418. Quaternion.prototype.asArray = function () {
  4419. return [this.x, this.y, this.z, this.w];
  4420. };
  4421. /**
  4422. * Check if two quaternions are equals
  4423. * @param otherQuaternion defines the second operand
  4424. * @return true if the current quaternion and the given one coordinates are strictly equals
  4425. */
  4426. Quaternion.prototype.equals = function (otherQuaternion) {
  4427. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4428. };
  4429. /**
  4430. * Clone the current quaternion
  4431. * @returns a new quaternion copied from the current one
  4432. */
  4433. Quaternion.prototype.clone = function () {
  4434. return new Quaternion(this.x, this.y, this.z, this.w);
  4435. };
  4436. /**
  4437. * Copy a quaternion to the current one
  4438. * @param other defines the other quaternion
  4439. * @returns the updated current quaternion
  4440. */
  4441. Quaternion.prototype.copyFrom = function (other) {
  4442. this.x = other.x;
  4443. this.y = other.y;
  4444. this.z = other.z;
  4445. this.w = other.w;
  4446. return this;
  4447. };
  4448. /**
  4449. * Updates the current quaternion with the given float coordinates
  4450. * @param x defines the x coordinate
  4451. * @param y defines the y coordinate
  4452. * @param z defines the z coordinate
  4453. * @param w defines the w coordinate
  4454. * @returns the updated current quaternion
  4455. */
  4456. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4457. this.x = x;
  4458. this.y = y;
  4459. this.z = z;
  4460. this.w = w;
  4461. return this;
  4462. };
  4463. /**
  4464. * Updates the current quaternion from the given float coordinates
  4465. * @param x defines the x coordinate
  4466. * @param y defines the y coordinate
  4467. * @param z defines the z coordinate
  4468. * @param w defines the w coordinate
  4469. * @returns the updated current quaternion
  4470. */
  4471. Quaternion.prototype.set = function (x, y, z, w) {
  4472. return this.copyFromFloats(x, y, z, w);
  4473. };
  4474. /**
  4475. * Adds two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4478. */
  4479. Quaternion.prototype.add = function (other) {
  4480. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4481. };
  4482. /**
  4483. * Add a quaternion to the current one
  4484. * @param other defines the quaternion to add
  4485. * @returns the current quaternion
  4486. */
  4487. Quaternion.prototype.addInPlace = function (other) {
  4488. this.x += other.x;
  4489. this.y += other.y;
  4490. this.z += other.z;
  4491. this.w += other.w;
  4492. return this;
  4493. };
  4494. /**
  4495. * Subtract two quaternions
  4496. * @param other defines the second operand
  4497. * @returns a new quaternion as the subtraction result of the given one from the current one
  4498. */
  4499. Quaternion.prototype.subtract = function (other) {
  4500. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4501. };
  4502. /**
  4503. * Multiplies the current quaternion by a scale factor
  4504. * @param value defines the scale factor
  4505. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4506. */
  4507. Quaternion.prototype.scale = function (value) {
  4508. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4509. };
  4510. /**
  4511. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4512. * @param scale defines the scale factor
  4513. * @param result defines the Quaternion object where to store the result
  4514. * @returns the unmodified current quaternion
  4515. */
  4516. Quaternion.prototype.scaleToRef = function (scale, result) {
  4517. result.x = this.x * scale;
  4518. result.y = this.y * scale;
  4519. result.z = this.z * scale;
  4520. result.w = this.w * scale;
  4521. return this;
  4522. };
  4523. /**
  4524. * Multiplies in place the current quaternion by a scale factor
  4525. * @param value defines the scale factor
  4526. * @returns the current modified quaternion
  4527. */
  4528. Quaternion.prototype.scaleInPlace = function (value) {
  4529. this.x *= value;
  4530. this.y *= value;
  4531. this.z *= value;
  4532. this.w *= value;
  4533. return this;
  4534. };
  4535. /**
  4536. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4537. * @param scale defines the scale factor
  4538. * @param result defines the Quaternion object where to store the result
  4539. * @returns the unmodified current quaternion
  4540. */
  4541. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4542. result.x += this.x * scale;
  4543. result.y += this.y * scale;
  4544. result.z += this.z * scale;
  4545. result.w += this.w * scale;
  4546. return this;
  4547. };
  4548. /**
  4549. * Multiplies two quaternions
  4550. * @param q1 defines the second operand
  4551. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4552. */
  4553. Quaternion.prototype.multiply = function (q1) {
  4554. var result = new Quaternion(0, 0, 0, 1.0);
  4555. this.multiplyToRef(q1, result);
  4556. return result;
  4557. };
  4558. /**
  4559. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4560. * @param q1 defines the second operand
  4561. * @param result defines the target quaternion
  4562. * @returns the current quaternion
  4563. */
  4564. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4565. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4566. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4567. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4568. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4569. result.copyFromFloats(x, y, z, w);
  4570. return this;
  4571. };
  4572. /**
  4573. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4574. * @param q1 defines the second operand
  4575. * @returns the currentupdated quaternion
  4576. */
  4577. Quaternion.prototype.multiplyInPlace = function (q1) {
  4578. this.multiplyToRef(q1, this);
  4579. return this;
  4580. };
  4581. /**
  4582. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4583. * @param ref defines the target quaternion
  4584. * @returns the current quaternion
  4585. */
  4586. Quaternion.prototype.conjugateToRef = function (ref) {
  4587. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4588. return this;
  4589. };
  4590. /**
  4591. * Conjugates in place (1-q) the current quaternion
  4592. * @returns the current updated quaternion
  4593. */
  4594. Quaternion.prototype.conjugateInPlace = function () {
  4595. this.x *= -1;
  4596. this.y *= -1;
  4597. this.z *= -1;
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates in place (1-q) the current quaternion
  4602. * @returns a new quaternion
  4603. */
  4604. Quaternion.prototype.conjugate = function () {
  4605. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4606. return result;
  4607. };
  4608. /**
  4609. * Gets length of current quaternion
  4610. * @returns the quaternion length (float)
  4611. */
  4612. Quaternion.prototype.length = function () {
  4613. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4614. };
  4615. /**
  4616. * Normalize in place the current quaternion
  4617. * @returns the current updated quaternion
  4618. */
  4619. Quaternion.prototype.normalize = function () {
  4620. var length = 1.0 / this.length();
  4621. this.x *= length;
  4622. this.y *= length;
  4623. this.z *= length;
  4624. this.w *= length;
  4625. return this;
  4626. };
  4627. /**
  4628. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4629. * @param order is a reserved parameter and is ignore for now
  4630. * @returns a new Vector3 containing the Euler angles
  4631. */
  4632. Quaternion.prototype.toEulerAngles = function (order) {
  4633. if (order === void 0) { order = "YZX"; }
  4634. var result = Vector3.Zero();
  4635. this.toEulerAnglesToRef(result, order);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4640. * @param result defines the vector which will be filled with the Euler angles
  4641. * @param order is a reserved parameter and is ignore for now
  4642. * @returns the current unchanged quaternion
  4643. */
  4644. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4645. if (order === void 0) { order = "YZX"; }
  4646. var qz = this.z;
  4647. var qx = this.x;
  4648. var qy = this.y;
  4649. var qw = this.w;
  4650. var sqw = qw * qw;
  4651. var sqz = qz * qz;
  4652. var sqx = qx * qx;
  4653. var sqy = qy * qy;
  4654. var zAxisY = qy * qz - qx * qw;
  4655. var limit = .4999999;
  4656. if (zAxisY < -limit) {
  4657. result.y = 2 * Math.atan2(qy, qw);
  4658. result.x = Math.PI / 2;
  4659. result.z = 0;
  4660. }
  4661. else if (zAxisY > limit) {
  4662. result.y = 2 * Math.atan2(qy, qw);
  4663. result.x = -Math.PI / 2;
  4664. result.z = 0;
  4665. }
  4666. else {
  4667. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4668. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4669. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4670. }
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the given rotation matrix with the current quaternion values
  4675. * @param result defines the target matrix
  4676. * @returns the current unchanged quaternion
  4677. */
  4678. Quaternion.prototype.toRotationMatrix = function (result) {
  4679. var xx = this.x * this.x;
  4680. var yy = this.y * this.y;
  4681. var zz = this.z * this.z;
  4682. var xy = this.x * this.y;
  4683. var zw = this.z * this.w;
  4684. var zx = this.z * this.x;
  4685. var yw = this.y * this.w;
  4686. var yz = this.y * this.z;
  4687. var xw = this.x * this.w;
  4688. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4689. result.m[1] = 2.0 * (xy + zw);
  4690. result.m[2] = 2.0 * (zx - yw);
  4691. result.m[3] = 0;
  4692. result.m[4] = 2.0 * (xy - zw);
  4693. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4694. result.m[6] = 2.0 * (yz + xw);
  4695. result.m[7] = 0;
  4696. result.m[8] = 2.0 * (zx + yw);
  4697. result.m[9] = 2.0 * (yz - xw);
  4698. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4699. result.m[11] = 0;
  4700. result.m[12] = 0;
  4701. result.m[13] = 0;
  4702. result.m[14] = 0;
  4703. result.m[15] = 1.0;
  4704. result._markAsUpdated();
  4705. return this;
  4706. };
  4707. /**
  4708. * Updates the current quaternion from the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @returns the current updated quaternion
  4711. */
  4712. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4713. Quaternion.FromRotationMatrixToRef(matrix, this);
  4714. return this;
  4715. };
  4716. // Statics
  4717. /**
  4718. * Creates a new quaternion from a rotation matrix
  4719. * @param matrix defines the source matrix
  4720. * @returns a new quaternion created from the given rotation matrix values
  4721. */
  4722. Quaternion.FromRotationMatrix = function (matrix) {
  4723. var result = new Quaternion();
  4724. Quaternion.FromRotationMatrixToRef(matrix, result);
  4725. return result;
  4726. };
  4727. /**
  4728. * Updates the given quaternion with the given rotation matrix values
  4729. * @param matrix defines the source matrix
  4730. * @param result defines the target quaternion
  4731. */
  4732. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4733. var data = matrix.m;
  4734. var m11 = data[0], m12 = data[4], m13 = data[8];
  4735. var m21 = data[1], m22 = data[5], m23 = data[9];
  4736. var m31 = data[2], m32 = data[6], m33 = data[10];
  4737. var trace = m11 + m22 + m33;
  4738. var s;
  4739. if (trace > 0) {
  4740. s = 0.5 / Math.sqrt(trace + 1.0);
  4741. result.w = 0.25 / s;
  4742. result.x = (m32 - m23) * s;
  4743. result.y = (m13 - m31) * s;
  4744. result.z = (m21 - m12) * s;
  4745. }
  4746. else if (m11 > m22 && m11 > m33) {
  4747. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4748. result.w = (m32 - m23) / s;
  4749. result.x = 0.25 * s;
  4750. result.y = (m12 + m21) / s;
  4751. result.z = (m13 + m31) / s;
  4752. }
  4753. else if (m22 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4755. result.w = (m13 - m31) / s;
  4756. result.x = (m12 + m21) / s;
  4757. result.y = 0.25 * s;
  4758. result.z = (m23 + m32) / s;
  4759. }
  4760. else {
  4761. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4762. result.w = (m21 - m12) / s;
  4763. result.x = (m13 + m31) / s;
  4764. result.y = (m23 + m32) / s;
  4765. result.z = 0.25 * s;
  4766. }
  4767. };
  4768. /**
  4769. * Returns the dot product (float) between the quaternions "left" and "right"
  4770. * @param left defines the left operand
  4771. * @param right defines the right operand
  4772. * @returns the dot product
  4773. */
  4774. Quaternion.Dot = function (left, right) {
  4775. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4776. };
  4777. /**
  4778. * Checks if the two quaternions are close to each other
  4779. * @param quat0 defines the first quaternion to check
  4780. * @param quat1 defines the second quaternion to check
  4781. * @returns true if the two quaternions are close to each other
  4782. */
  4783. Quaternion.AreClose = function (quat0, quat1) {
  4784. var dot = Quaternion.Dot(quat0, quat1);
  4785. return dot >= 0;
  4786. };
  4787. /**
  4788. * Creates an empty quaternion
  4789. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4790. */
  4791. Quaternion.Zero = function () {
  4792. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4793. };
  4794. /**
  4795. * Inverse a given quaternion
  4796. * @param q defines the source quaternion
  4797. * @returns a new quaternion as the inverted current quaternion
  4798. */
  4799. Quaternion.Inverse = function (q) {
  4800. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4801. };
  4802. /**
  4803. * Creates an identity quaternion
  4804. * @returns the identity quaternion
  4805. */
  4806. Quaternion.Identity = function () {
  4807. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4808. };
  4809. /**
  4810. * Gets a boolean indicating if the given quaternion is identity
  4811. * @param quaternion defines the quaternion to check
  4812. * @returns true if the quaternion is identity
  4813. */
  4814. Quaternion.IsIdentity = function (quaternion) {
  4815. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4816. };
  4817. /**
  4818. * Creates a quaternion from a rotation around an axis
  4819. * @param axis defines the axis to use
  4820. * @param angle defines the angle to use
  4821. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4822. */
  4823. Quaternion.RotationAxis = function (axis, angle) {
  4824. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4825. };
  4826. /**
  4827. * Creates a rotation around an axis and stores it into the given quaternion
  4828. * @param axis defines the axis to use
  4829. * @param angle defines the angle to use
  4830. * @param result defines the target quaternion
  4831. * @returns the target quaternion
  4832. */
  4833. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4834. var sin = Math.sin(angle / 2);
  4835. axis.normalize();
  4836. result.w = Math.cos(angle / 2);
  4837. result.x = axis.x * sin;
  4838. result.y = axis.y * sin;
  4839. result.z = axis.z * sin;
  4840. return result;
  4841. };
  4842. /**
  4843. * Creates a new quaternion from data stored into an array
  4844. * @param array defines the data source
  4845. * @param offset defines the offset in the source array where the data starts
  4846. * @returns a new quaternion
  4847. */
  4848. Quaternion.FromArray = function (array, offset) {
  4849. if (!offset) {
  4850. offset = 0;
  4851. }
  4852. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4853. };
  4854. /**
  4855. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4856. * @param yaw defines the rotation around Y axis
  4857. * @param pitch defines the rotation around X axis
  4858. * @param roll defines the rotation around Z axis
  4859. * @returns the new quaternion
  4860. */
  4861. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4862. var q = new Quaternion();
  4863. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4864. return q;
  4865. };
  4866. /**
  4867. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4868. * @param yaw defines the rotation around Y axis
  4869. * @param pitch defines the rotation around X axis
  4870. * @param roll defines the rotation around Z axis
  4871. * @param result defines the target quaternion
  4872. */
  4873. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4874. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4875. var halfRoll = roll * 0.5;
  4876. var halfPitch = pitch * 0.5;
  4877. var halfYaw = yaw * 0.5;
  4878. var sinRoll = Math.sin(halfRoll);
  4879. var cosRoll = Math.cos(halfRoll);
  4880. var sinPitch = Math.sin(halfPitch);
  4881. var cosPitch = Math.cos(halfPitch);
  4882. var sinYaw = Math.sin(halfYaw);
  4883. var cosYaw = Math.cos(halfYaw);
  4884. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4885. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4886. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4887. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4888. };
  4889. /**
  4890. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4891. * @param alpha defines the rotation around first axis
  4892. * @param beta defines the rotation around second axis
  4893. * @param gamma defines the rotation around third axis
  4894. * @returns the new quaternion
  4895. */
  4896. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4897. var result = new Quaternion();
  4898. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4899. return result;
  4900. };
  4901. /**
  4902. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4903. * @param alpha defines the rotation around first axis
  4904. * @param beta defines the rotation around second axis
  4905. * @param gamma defines the rotation around third axis
  4906. * @param result defines the target quaternion
  4907. */
  4908. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4909. // Produces a quaternion from Euler angles in the z-x-z orientation
  4910. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4911. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4912. var halfBeta = beta * 0.5;
  4913. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4914. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4915. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4916. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4917. };
  4918. /**
  4919. * 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)
  4920. * @param axis1 defines the first axis
  4921. * @param axis2 defines the second axis
  4922. * @param axis3 defines the third axis
  4923. * @returns the new quaternion
  4924. */
  4925. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4926. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4927. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4928. return quat;
  4929. };
  4930. /**
  4931. * 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
  4932. * @param axis1 defines the first axis
  4933. * @param axis2 defines the second axis
  4934. * @param axis3 defines the third axis
  4935. * @param ref defines the target quaternion
  4936. */
  4937. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4938. var rotMat = MathTmp.Matrix[0];
  4939. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4940. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4941. };
  4942. /**
  4943. * Interpolates between two quaternions
  4944. * @param left defines first quaternion
  4945. * @param right defines second quaternion
  4946. * @param amount defines the gradient to use
  4947. * @returns the new interpolated quaternion
  4948. */
  4949. Quaternion.Slerp = function (left, right, amount) {
  4950. var result = Quaternion.Identity();
  4951. Quaternion.SlerpToRef(left, right, amount, result);
  4952. return result;
  4953. };
  4954. /**
  4955. * Interpolates between two quaternions and stores it into a target quaternion
  4956. * @param left defines first quaternion
  4957. * @param right defines second quaternion
  4958. * @param amount defines the gradient to use
  4959. * @param result defines the target quaternion
  4960. */
  4961. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4962. var num2;
  4963. var num3;
  4964. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4965. var flag = false;
  4966. if (num4 < 0) {
  4967. flag = true;
  4968. num4 = -num4;
  4969. }
  4970. if (num4 > 0.999999) {
  4971. num3 = 1 - amount;
  4972. num2 = flag ? -amount : amount;
  4973. }
  4974. else {
  4975. var num5 = Math.acos(num4);
  4976. var num6 = (1.0 / Math.sin(num5));
  4977. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4978. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4979. }
  4980. result.x = (num3 * left.x) + (num2 * right.x);
  4981. result.y = (num3 * left.y) + (num2 * right.y);
  4982. result.z = (num3 * left.z) + (num2 * right.z);
  4983. result.w = (num3 * left.w) + (num2 * right.w);
  4984. };
  4985. /**
  4986. * Interpolate between two quaternions using Hermite interpolation
  4987. * @param value1 defines first quaternion
  4988. * @param tangent1 defines the incoming tangent
  4989. * @param value2 defines second quaternion
  4990. * @param tangent2 defines the outgoing tangent
  4991. * @param amount defines the target quaternion
  4992. * @returns the new interpolated quaternion
  4993. */
  4994. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4995. var squared = amount * amount;
  4996. var cubed = amount * squared;
  4997. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4998. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4999. var part3 = (cubed - (2.0 * squared)) + amount;
  5000. var part4 = cubed - squared;
  5001. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5002. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5003. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5004. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5005. return new Quaternion(x, y, z, w);
  5006. };
  5007. return Quaternion;
  5008. }());
  5009. BABYLON.Quaternion = Quaternion;
  5010. /**
  5011. * Class used to store matrix data (4x4)
  5012. */
  5013. var Matrix = /** @class */ (function () {
  5014. /**
  5015. * Creates an empty matrix (filled with zeros)
  5016. */
  5017. function Matrix() {
  5018. this._isIdentity = false;
  5019. this._isIdentityDirty = true;
  5020. /**
  5021. * Gets or sets the internal data of the matrix
  5022. */
  5023. this.m = new Float32Array(16);
  5024. this._markAsUpdated();
  5025. }
  5026. /** @hidden */
  5027. Matrix.prototype._markAsUpdated = function () {
  5028. this.updateFlag = Matrix._updateFlagSeed++;
  5029. this._isIdentityDirty = true;
  5030. };
  5031. // Properties
  5032. /**
  5033. * Check if the current matrix is indentity
  5034. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5035. * @returns true is the matrix is the identity matrix
  5036. */
  5037. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5038. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5039. if (this._isIdentityDirty) {
  5040. this._isIdentityDirty = false;
  5041. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5042. this._isIdentity = false;
  5043. }
  5044. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5045. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5046. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5047. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5048. this._isIdentity = false;
  5049. }
  5050. else {
  5051. this._isIdentity = true;
  5052. }
  5053. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5054. this._isIdentity = false;
  5055. }
  5056. }
  5057. return this._isIdentity;
  5058. };
  5059. /**
  5060. * Gets the determinant of the matrix
  5061. * @returns the matrix determinant
  5062. */
  5063. Matrix.prototype.determinant = function () {
  5064. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5065. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5066. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5067. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5068. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5069. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5070. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5071. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5072. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5073. };
  5074. // Methods
  5075. /**
  5076. * Returns the matrix as a Float32Array
  5077. * @returns the matrix underlying array
  5078. */
  5079. Matrix.prototype.toArray = function () {
  5080. return this.m;
  5081. };
  5082. /**
  5083. * Returns the matrix as a Float32Array
  5084. * @returns the matrix underlying array.
  5085. */
  5086. Matrix.prototype.asArray = function () {
  5087. return this.toArray();
  5088. };
  5089. /**
  5090. * Inverts the current matrix in place
  5091. * @returns the current inverted matrix
  5092. */
  5093. Matrix.prototype.invert = function () {
  5094. this.invertToRef(this);
  5095. return this;
  5096. };
  5097. /**
  5098. * Sets all the matrix elements to zero
  5099. * @returns the current matrix
  5100. */
  5101. Matrix.prototype.reset = function () {
  5102. for (var index = 0; index < 16; index++) {
  5103. this.m[index] = 0.0;
  5104. }
  5105. this._markAsUpdated();
  5106. return this;
  5107. };
  5108. /**
  5109. * Adds the current matrix with a second one
  5110. * @param other defines the matrix to add
  5111. * @returns a new matrix as the addition of the current matrix and the given one
  5112. */
  5113. Matrix.prototype.add = function (other) {
  5114. var result = new Matrix();
  5115. this.addToRef(other, result);
  5116. return result;
  5117. };
  5118. /**
  5119. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5120. * @param other defines the matrix to add
  5121. * @param result defines the target matrix
  5122. * @returns the current matrix
  5123. */
  5124. Matrix.prototype.addToRef = function (other, result) {
  5125. for (var index = 0; index < 16; index++) {
  5126. result.m[index] = this.m[index] + other.m[index];
  5127. }
  5128. result._markAsUpdated();
  5129. return this;
  5130. };
  5131. /**
  5132. * Adds in place the given matrix to the current matrix
  5133. * @param other defines the second operand
  5134. * @returns the current updated matrix
  5135. */
  5136. Matrix.prototype.addToSelf = function (other) {
  5137. for (var index = 0; index < 16; index++) {
  5138. this.m[index] += other.m[index];
  5139. }
  5140. this._markAsUpdated();
  5141. return this;
  5142. };
  5143. /**
  5144. * Sets the given matrix to the current inverted Matrix
  5145. * @param other defines the target matrix
  5146. * @returns the unmodified current matrix
  5147. */
  5148. Matrix.prototype.invertToRef = function (other) {
  5149. var l1 = this.m[0];
  5150. var l2 = this.m[1];
  5151. var l3 = this.m[2];
  5152. var l4 = this.m[3];
  5153. var l5 = this.m[4];
  5154. var l6 = this.m[5];
  5155. var l7 = this.m[6];
  5156. var l8 = this.m[7];
  5157. var l9 = this.m[8];
  5158. var l10 = this.m[9];
  5159. var l11 = this.m[10];
  5160. var l12 = this.m[11];
  5161. var l13 = this.m[12];
  5162. var l14 = this.m[13];
  5163. var l15 = this.m[14];
  5164. var l16 = this.m[15];
  5165. var l17 = (l11 * l16) - (l12 * l15);
  5166. var l18 = (l10 * l16) - (l12 * l14);
  5167. var l19 = (l10 * l15) - (l11 * l14);
  5168. var l20 = (l9 * l16) - (l12 * l13);
  5169. var l21 = (l9 * l15) - (l11 * l13);
  5170. var l22 = (l9 * l14) - (l10 * l13);
  5171. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5172. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5173. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5174. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5175. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5176. var l28 = (l7 * l16) - (l8 * l15);
  5177. var l29 = (l6 * l16) - (l8 * l14);
  5178. var l30 = (l6 * l15) - (l7 * l14);
  5179. var l31 = (l5 * l16) - (l8 * l13);
  5180. var l32 = (l5 * l15) - (l7 * l13);
  5181. var l33 = (l5 * l14) - (l6 * l13);
  5182. var l34 = (l7 * l12) - (l8 * l11);
  5183. var l35 = (l6 * l12) - (l8 * l10);
  5184. var l36 = (l6 * l11) - (l7 * l10);
  5185. var l37 = (l5 * l12) - (l8 * l9);
  5186. var l38 = (l5 * l11) - (l7 * l9);
  5187. var l39 = (l5 * l10) - (l6 * l9);
  5188. other.m[0] = l23 * l27;
  5189. other.m[4] = l24 * l27;
  5190. other.m[8] = l25 * l27;
  5191. other.m[12] = l26 * l27;
  5192. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5193. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5194. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5195. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5196. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5197. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5198. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5199. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5200. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5201. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5202. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5203. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5204. other._markAsUpdated();
  5205. return this;
  5206. };
  5207. /**
  5208. * Inserts the translation vector (using 3 floats) in the current matrix
  5209. * @param x defines the 1st component of the translation
  5210. * @param y defines the 2nd component of the translation
  5211. * @param z defines the 3rd component of the translation
  5212. * @returns the current updated matrix
  5213. */
  5214. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5215. this.m[12] = x;
  5216. this.m[13] = y;
  5217. this.m[14] = z;
  5218. this._markAsUpdated();
  5219. return this;
  5220. };
  5221. /**
  5222. * Inserts the translation vector in the current matrix
  5223. * @param vector3 defines the translation to insert
  5224. * @returns the current updated matrix
  5225. */
  5226. Matrix.prototype.setTranslation = function (vector3) {
  5227. this.m[12] = vector3.x;
  5228. this.m[13] = vector3.y;
  5229. this.m[14] = vector3.z;
  5230. this._markAsUpdated();
  5231. return this;
  5232. };
  5233. /**
  5234. * Gets the translation value of the current matrix
  5235. * @returns a new Vector3 as the extracted translation from the matrix
  5236. */
  5237. Matrix.prototype.getTranslation = function () {
  5238. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5239. };
  5240. /**
  5241. * Fill a Vector3 with the extracted translation from the matrix
  5242. * @param result defines the Vector3 where to store the translation
  5243. * @returns the current matrix
  5244. */
  5245. Matrix.prototype.getTranslationToRef = function (result) {
  5246. result.x = this.m[12];
  5247. result.y = this.m[13];
  5248. result.z = this.m[14];
  5249. return this;
  5250. };
  5251. /**
  5252. * Remove rotation and scaling part from the matrix
  5253. * @returns the updated matrix
  5254. */
  5255. Matrix.prototype.removeRotationAndScaling = function () {
  5256. this.setRowFromFloats(0, 1, 0, 0, 0);
  5257. this.setRowFromFloats(1, 0, 1, 0, 0);
  5258. this.setRowFromFloats(2, 0, 0, 1, 0);
  5259. return this;
  5260. };
  5261. /**
  5262. * Multiply two matrices
  5263. * @param other defines the second operand
  5264. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5265. */
  5266. Matrix.prototype.multiply = function (other) {
  5267. var result = new Matrix();
  5268. this.multiplyToRef(other, result);
  5269. return result;
  5270. };
  5271. /**
  5272. * Copy the current matrix from the given one
  5273. * @param other defines the source matrix
  5274. * @returns the current updated matrix
  5275. */
  5276. Matrix.prototype.copyFrom = function (other) {
  5277. for (var index = 0; index < 16; index++) {
  5278. this.m[index] = other.m[index];
  5279. }
  5280. this._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Populates the given array from the starting index with the current matrix values
  5285. * @param array defines the target array
  5286. * @param offset defines the offset in the target array where to start storing values
  5287. * @returns the current matrix
  5288. */
  5289. Matrix.prototype.copyToArray = function (array, offset) {
  5290. if (offset === void 0) { offset = 0; }
  5291. for (var index = 0; index < 16; index++) {
  5292. array[offset + index] = this.m[index];
  5293. }
  5294. return this;
  5295. };
  5296. /**
  5297. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5298. * @param other defines the second operand
  5299. * @param result defines the matrix where to store the multiplication
  5300. * @returns the current matrix
  5301. */
  5302. Matrix.prototype.multiplyToRef = function (other, result) {
  5303. this.multiplyToArray(other, result.m, 0);
  5304. result._markAsUpdated();
  5305. return this;
  5306. };
  5307. /**
  5308. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5309. * @param other defines the second operand
  5310. * @param result defines the array where to store the multiplication
  5311. * @param offset defines the offset in the target array where to start storing values
  5312. * @returns the current matrix
  5313. */
  5314. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5315. var tm0 = this.m[0];
  5316. var tm1 = this.m[1];
  5317. var tm2 = this.m[2];
  5318. var tm3 = this.m[3];
  5319. var tm4 = this.m[4];
  5320. var tm5 = this.m[5];
  5321. var tm6 = this.m[6];
  5322. var tm7 = this.m[7];
  5323. var tm8 = this.m[8];
  5324. var tm9 = this.m[9];
  5325. var tm10 = this.m[10];
  5326. var tm11 = this.m[11];
  5327. var tm12 = this.m[12];
  5328. var tm13 = this.m[13];
  5329. var tm14 = this.m[14];
  5330. var tm15 = this.m[15];
  5331. var om0 = other.m[0];
  5332. var om1 = other.m[1];
  5333. var om2 = other.m[2];
  5334. var om3 = other.m[3];
  5335. var om4 = other.m[4];
  5336. var om5 = other.m[5];
  5337. var om6 = other.m[6];
  5338. var om7 = other.m[7];
  5339. var om8 = other.m[8];
  5340. var om9 = other.m[9];
  5341. var om10 = other.m[10];
  5342. var om11 = other.m[11];
  5343. var om12 = other.m[12];
  5344. var om13 = other.m[13];
  5345. var om14 = other.m[14];
  5346. var om15 = other.m[15];
  5347. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5348. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5349. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5350. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5351. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5352. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5353. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5354. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5355. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5356. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5357. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5358. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5359. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5360. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5361. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5362. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5363. return this;
  5364. };
  5365. /**
  5366. * Check equality between this matrix and a second one
  5367. * @param value defines the second matrix to compare
  5368. * @returns true is the current matrix and the given one values are strictly equal
  5369. */
  5370. Matrix.prototype.equals = function (value) {
  5371. return value &&
  5372. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5373. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5374. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5375. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5376. };
  5377. /**
  5378. * Clone the current matrix
  5379. * @returns a new matrix from the current matrix
  5380. */
  5381. Matrix.prototype.clone = function () {
  5382. 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]);
  5383. };
  5384. /**
  5385. * Returns the name of the current matrix class
  5386. * @returns the string "Matrix"
  5387. */
  5388. Matrix.prototype.getClassName = function () {
  5389. return "Matrix";
  5390. };
  5391. /**
  5392. * Gets the hash code of the current matrix
  5393. * @returns the hash code
  5394. */
  5395. Matrix.prototype.getHashCode = function () {
  5396. var hash = this.m[0] || 0;
  5397. for (var i = 1; i < 16; i++) {
  5398. hash = (hash * 397) ^ (this.m[i] || 0);
  5399. }
  5400. return hash;
  5401. };
  5402. /**
  5403. * Decomposes the current Matrix into a translation, rotation and scaling components
  5404. * @param scale defines the scale vector3 given as a reference to update
  5405. * @param rotation defines the rotation quaternion given as a reference to update
  5406. * @param translation defines the translation vector3 given as a reference to update
  5407. * @returns true if operation was successful
  5408. */
  5409. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5410. if (translation) {
  5411. translation.x = this.m[12];
  5412. translation.y = this.m[13];
  5413. translation.z = this.m[14];
  5414. }
  5415. scale = scale || MathTmp.Vector3[0];
  5416. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5417. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5418. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5419. if (this.determinant() <= 0) {
  5420. scale.y *= -1;
  5421. }
  5422. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5423. if (rotation) {
  5424. rotation.x = 0;
  5425. rotation.y = 0;
  5426. rotation.z = 0;
  5427. rotation.w = 1;
  5428. }
  5429. return false;
  5430. }
  5431. if (rotation) {
  5432. 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]);
  5433. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5434. }
  5435. return true;
  5436. };
  5437. /**
  5438. * Gets specific row of the matrix
  5439. * @param index defines the number of the row to get
  5440. * @returns the index-th row of the current matrix as a new Vector4
  5441. */
  5442. Matrix.prototype.getRow = function (index) {
  5443. if (index < 0 || index > 3) {
  5444. return null;
  5445. }
  5446. var i = index * 4;
  5447. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5448. };
  5449. /**
  5450. * Sets the index-th row of the current matrix to the vector4 values
  5451. * @param index defines the number of the row to set
  5452. * @param row defines the target vector4
  5453. * @returns the updated current matrix
  5454. */
  5455. Matrix.prototype.setRow = function (index, row) {
  5456. if (index < 0 || index > 3) {
  5457. return this;
  5458. }
  5459. var i = index * 4;
  5460. this.m[i + 0] = row.x;
  5461. this.m[i + 1] = row.y;
  5462. this.m[i + 2] = row.z;
  5463. this.m[i + 3] = row.w;
  5464. this._markAsUpdated();
  5465. return this;
  5466. };
  5467. /**
  5468. * Compute the transpose of the matrix
  5469. * @returns the new transposed matrix
  5470. */
  5471. Matrix.prototype.transpose = function () {
  5472. return Matrix.Transpose(this);
  5473. };
  5474. /**
  5475. * Compute the transpose of the matrix and store it in a given matrix
  5476. * @param result defines the target matrix
  5477. * @returns the current matrix
  5478. */
  5479. Matrix.prototype.transposeToRef = function (result) {
  5480. Matrix.TransposeToRef(this, result);
  5481. return this;
  5482. };
  5483. /**
  5484. * Sets the index-th row of the current matrix with the given 4 x float values
  5485. * @param index defines the row index
  5486. * @param x defines the x component to set
  5487. * @param y defines the y component to set
  5488. * @param z defines the z component to set
  5489. * @param w defines the w component to set
  5490. * @returns the updated current matrix
  5491. */
  5492. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5493. if (index < 0 || index > 3) {
  5494. return this;
  5495. }
  5496. var i = index * 4;
  5497. this.m[i + 0] = x;
  5498. this.m[i + 1] = y;
  5499. this.m[i + 2] = z;
  5500. this.m[i + 3] = w;
  5501. this._markAsUpdated();
  5502. return this;
  5503. };
  5504. /**
  5505. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5506. * @param scale defines the scale factor
  5507. * @returns a new matrix
  5508. */
  5509. Matrix.prototype.scale = function (scale) {
  5510. var result = new Matrix();
  5511. this.scaleToRef(scale, result);
  5512. return result;
  5513. };
  5514. /**
  5515. * Scale the current matrix values by a factor to a given result matrix
  5516. * @param scale defines the scale factor
  5517. * @param result defines the matrix to store the result
  5518. * @returns the current matrix
  5519. */
  5520. Matrix.prototype.scaleToRef = function (scale, result) {
  5521. for (var index = 0; index < 16; index++) {
  5522. result.m[index] = this.m[index] * scale;
  5523. }
  5524. result._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Scale the current matrix values by a factor and add the result to a given matrix
  5529. * @param scale defines the scale factor
  5530. * @param result defines the Matrix to store the result
  5531. * @returns the current matrix
  5532. */
  5533. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5534. for (var index = 0; index < 16; index++) {
  5535. result.m[index] += this.m[index] * scale;
  5536. }
  5537. result._markAsUpdated();
  5538. return this;
  5539. };
  5540. /**
  5541. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5542. * @param ref matrix to store the result
  5543. */
  5544. Matrix.prototype.toNormalMatrix = function (ref) {
  5545. this.invertToRef(ref);
  5546. ref.transpose();
  5547. var m = ref.m;
  5548. 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);
  5549. };
  5550. /**
  5551. * Gets only rotation part of the current matrix
  5552. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5553. */
  5554. Matrix.prototype.getRotationMatrix = function () {
  5555. var result = Matrix.Identity();
  5556. this.getRotationMatrixToRef(result);
  5557. return result;
  5558. };
  5559. /**
  5560. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5561. * @param result defines the target matrix to store data to
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5565. var m = this.m;
  5566. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5567. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5568. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5569. if (this.determinant() <= 0) {
  5570. sy *= -1;
  5571. }
  5572. if (sx === 0 || sy === 0 || sz === 0) {
  5573. Matrix.IdentityToRef(result);
  5574. }
  5575. else {
  5576. 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);
  5577. }
  5578. return this;
  5579. };
  5580. // Statics
  5581. /**
  5582. * Creates a matrix from an array
  5583. * @param array defines the source array
  5584. * @param offset defines an offset in the source array
  5585. * @returns a new Matrix set from the starting index of the given array
  5586. */
  5587. Matrix.FromArray = function (array, offset) {
  5588. var result = new Matrix();
  5589. if (!offset) {
  5590. offset = 0;
  5591. }
  5592. Matrix.FromArrayToRef(array, offset, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Copy the content of an array into a given matrix
  5597. * @param array defines the source array
  5598. * @param offset defines an offset in the source array
  5599. * @param result defines the target matrix
  5600. */
  5601. Matrix.FromArrayToRef = function (array, offset, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = array[index + offset];
  5604. }
  5605. result._markAsUpdated();
  5606. };
  5607. /**
  5608. * Stores an array into a matrix after having multiplied each component by a given factor
  5609. * @param array defines the source array
  5610. * @param offset defines the offset in the source array
  5611. * @param scale defines the scaling factor
  5612. * @param result defines the target matrix
  5613. */
  5614. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5615. for (var index = 0; index < 16; index++) {
  5616. result.m[index] = array[index + offset] * scale;
  5617. }
  5618. result._markAsUpdated();
  5619. };
  5620. /**
  5621. * Stores a list of values (16) inside a given matrix
  5622. * @param initialM11 defines 1st value of 1st row
  5623. * @param initialM12 defines 2nd value of 1st row
  5624. * @param initialM13 defines 3rd value of 1st row
  5625. * @param initialM14 defines 4th value of 1st row
  5626. * @param initialM21 defines 1st value of 2nd row
  5627. * @param initialM22 defines 2nd value of 2nd row
  5628. * @param initialM23 defines 3rd value of 2nd row
  5629. * @param initialM24 defines 4th value of 2nd row
  5630. * @param initialM31 defines 1st value of 3rd row
  5631. * @param initialM32 defines 2nd value of 3rd row
  5632. * @param initialM33 defines 3rd value of 3rd row
  5633. * @param initialM34 defines 4th value of 3rd row
  5634. * @param initialM41 defines 1st value of 4th row
  5635. * @param initialM42 defines 2nd value of 4th row
  5636. * @param initialM43 defines 3rd value of 4th row
  5637. * @param initialM44 defines 4th value of 4th row
  5638. * @param result defines the target matrix
  5639. */
  5640. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5641. result.m[0] = initialM11;
  5642. result.m[1] = initialM12;
  5643. result.m[2] = initialM13;
  5644. result.m[3] = initialM14;
  5645. result.m[4] = initialM21;
  5646. result.m[5] = initialM22;
  5647. result.m[6] = initialM23;
  5648. result.m[7] = initialM24;
  5649. result.m[8] = initialM31;
  5650. result.m[9] = initialM32;
  5651. result.m[10] = initialM33;
  5652. result.m[11] = initialM34;
  5653. result.m[12] = initialM41;
  5654. result.m[13] = initialM42;
  5655. result.m[14] = initialM43;
  5656. result.m[15] = initialM44;
  5657. result._markAsUpdated();
  5658. };
  5659. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5660. /**
  5661. * Gets an identity matrix that must not be updated
  5662. */
  5663. get: function () {
  5664. return Matrix._identityReadOnly;
  5665. },
  5666. enumerable: true,
  5667. configurable: true
  5668. });
  5669. /**
  5670. * Creates new matrix from a list of values (16)
  5671. * @param initialM11 defines 1st value of 1st row
  5672. * @param initialM12 defines 2nd value of 1st row
  5673. * @param initialM13 defines 3rd value of 1st row
  5674. * @param initialM14 defines 4th value of 1st row
  5675. * @param initialM21 defines 1st value of 2nd row
  5676. * @param initialM22 defines 2nd value of 2nd row
  5677. * @param initialM23 defines 3rd value of 2nd row
  5678. * @param initialM24 defines 4th value of 2nd row
  5679. * @param initialM31 defines 1st value of 3rd row
  5680. * @param initialM32 defines 2nd value of 3rd row
  5681. * @param initialM33 defines 3rd value of 3rd row
  5682. * @param initialM34 defines 4th value of 3rd row
  5683. * @param initialM41 defines 1st value of 4th row
  5684. * @param initialM42 defines 2nd value of 4th row
  5685. * @param initialM43 defines 3rd value of 4th row
  5686. * @param initialM44 defines 4th value of 4th row
  5687. * @returns the new matrix
  5688. */
  5689. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5690. var result = new Matrix();
  5691. result.m[0] = initialM11;
  5692. result.m[1] = initialM12;
  5693. result.m[2] = initialM13;
  5694. result.m[3] = initialM14;
  5695. result.m[4] = initialM21;
  5696. result.m[5] = initialM22;
  5697. result.m[6] = initialM23;
  5698. result.m[7] = initialM24;
  5699. result.m[8] = initialM31;
  5700. result.m[9] = initialM32;
  5701. result.m[10] = initialM33;
  5702. result.m[11] = initialM34;
  5703. result.m[12] = initialM41;
  5704. result.m[13] = initialM42;
  5705. result.m[14] = initialM43;
  5706. result.m[15] = initialM44;
  5707. return result;
  5708. };
  5709. /**
  5710. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5711. * @param scale defines the scale vector3
  5712. * @param rotation defines the rotation quaternion
  5713. * @param translation defines the translation vector3
  5714. * @returns a new matrix
  5715. */
  5716. Matrix.Compose = function (scale, rotation, translation) {
  5717. var result = Matrix.Identity();
  5718. Matrix.ComposeToRef(scale, rotation, translation, result);
  5719. return result;
  5720. };
  5721. /**
  5722. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5723. * @param scale defines the scale vector3
  5724. * @param rotation defines the rotation quaternion
  5725. * @param translation defines the translation vector3
  5726. * @param result defines the target matrix
  5727. */
  5728. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5729. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5730. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5731. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5732. result.setTranslation(translation);
  5733. };
  5734. /**
  5735. * Creates a new identity matrix
  5736. * @returns a new identity matrix
  5737. */
  5738. Matrix.Identity = function () {
  5739. 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);
  5740. };
  5741. /**
  5742. * Creates a new identity matrix and stores the result in a given matrix
  5743. * @param result defines the target matrix
  5744. */
  5745. Matrix.IdentityToRef = function (result) {
  5746. 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);
  5747. };
  5748. /**
  5749. * Creates a new zero matrix
  5750. * @returns a new zero matrix
  5751. */
  5752. Matrix.Zero = function () {
  5753. 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);
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the X axis
  5757. * @param angle defines the angle (in radians) to use
  5758. * @return the new matrix
  5759. */
  5760. Matrix.RotationX = function (angle) {
  5761. var result = new Matrix();
  5762. Matrix.RotationXToRef(angle, result);
  5763. return result;
  5764. };
  5765. /**
  5766. * Creates a new matrix as the invert of a given matrix
  5767. * @param source defines the source matrix
  5768. * @returns the new matrix
  5769. */
  5770. Matrix.Invert = function (source) {
  5771. var result = new Matrix();
  5772. source.invertToRef(result);
  5773. return result;
  5774. };
  5775. /**
  5776. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5777. * @param angle defines the angle (in radians) to use
  5778. * @param result defines the target matrix
  5779. */
  5780. Matrix.RotationXToRef = function (angle, result) {
  5781. var s = Math.sin(angle);
  5782. var c = Math.cos(angle);
  5783. result.m[0] = 1.0;
  5784. result.m[15] = 1.0;
  5785. result.m[5] = c;
  5786. result.m[10] = c;
  5787. result.m[9] = -s;
  5788. result.m[6] = s;
  5789. result.m[1] = 0.0;
  5790. result.m[2] = 0.0;
  5791. result.m[3] = 0.0;
  5792. result.m[4] = 0.0;
  5793. result.m[7] = 0.0;
  5794. result.m[8] = 0.0;
  5795. result.m[11] = 0.0;
  5796. result.m[12] = 0.0;
  5797. result.m[13] = 0.0;
  5798. result.m[14] = 0.0;
  5799. result._markAsUpdated();
  5800. };
  5801. /**
  5802. * Creates a new rotation matrix for "angle" radians around the Y axis
  5803. * @param angle defines the angle (in radians) to use
  5804. * @return the new matrix
  5805. */
  5806. Matrix.RotationY = function (angle) {
  5807. var result = new Matrix();
  5808. Matrix.RotationYToRef(angle, result);
  5809. return result;
  5810. };
  5811. /**
  5812. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5813. * @param angle defines the angle (in radians) to use
  5814. * @param result defines the target matrix
  5815. */
  5816. Matrix.RotationYToRef = function (angle, result) {
  5817. var s = Math.sin(angle);
  5818. var c = Math.cos(angle);
  5819. result.m[5] = 1.0;
  5820. result.m[15] = 1.0;
  5821. result.m[0] = c;
  5822. result.m[2] = -s;
  5823. result.m[8] = s;
  5824. result.m[10] = c;
  5825. result.m[1] = 0.0;
  5826. result.m[3] = 0.0;
  5827. result.m[4] = 0.0;
  5828. result.m[6] = 0.0;
  5829. result.m[7] = 0.0;
  5830. result.m[9] = 0.0;
  5831. result.m[11] = 0.0;
  5832. result.m[12] = 0.0;
  5833. result.m[13] = 0.0;
  5834. result.m[14] = 0.0;
  5835. result._markAsUpdated();
  5836. };
  5837. /**
  5838. * Creates a new rotation matrix for "angle" radians around the Z axis
  5839. * @param angle defines the angle (in radians) to use
  5840. * @return the new matrix
  5841. */
  5842. Matrix.RotationZ = function (angle) {
  5843. var result = new Matrix();
  5844. Matrix.RotationZToRef(angle, result);
  5845. return result;
  5846. };
  5847. /**
  5848. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5849. * @param angle defines the angle (in radians) to use
  5850. * @param result defines the target matrix
  5851. */
  5852. Matrix.RotationZToRef = function (angle, result) {
  5853. var s = Math.sin(angle);
  5854. var c = Math.cos(angle);
  5855. result.m[10] = 1.0;
  5856. result.m[15] = 1.0;
  5857. result.m[0] = c;
  5858. result.m[1] = s;
  5859. result.m[4] = -s;
  5860. result.m[5] = c;
  5861. result.m[2] = 0.0;
  5862. result.m[3] = 0.0;
  5863. result.m[6] = 0.0;
  5864. result.m[7] = 0.0;
  5865. result.m[8] = 0.0;
  5866. result.m[9] = 0.0;
  5867. result.m[11] = 0.0;
  5868. result.m[12] = 0.0;
  5869. result.m[13] = 0.0;
  5870. result.m[14] = 0.0;
  5871. result._markAsUpdated();
  5872. };
  5873. /**
  5874. * Creates a new rotation matrix for "angle" radians around the given axis
  5875. * @param axis defines the axis to use
  5876. * @param angle defines the angle (in radians) to use
  5877. * @return the new matrix
  5878. */
  5879. Matrix.RotationAxis = function (axis, angle) {
  5880. var result = Matrix.Zero();
  5881. Matrix.RotationAxisToRef(axis, angle, result);
  5882. return result;
  5883. };
  5884. /**
  5885. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5886. * @param axis defines the axis to use
  5887. * @param angle defines the angle (in radians) to use
  5888. * @param result defines the target matrix
  5889. */
  5890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5891. var s = Math.sin(-angle);
  5892. var c = Math.cos(-angle);
  5893. var c1 = 1 - c;
  5894. axis.normalize();
  5895. result.m[0] = (axis.x * axis.x) * c1 + c;
  5896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5898. result.m[3] = 0.0;
  5899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5900. result.m[5] = (axis.y * axis.y) * c1 + c;
  5901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5902. result.m[7] = 0.0;
  5903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5905. result.m[10] = (axis.z * axis.z) * c1 + c;
  5906. result.m[11] = 0.0;
  5907. result.m[15] = 1.0;
  5908. result._markAsUpdated();
  5909. };
  5910. /**
  5911. * Creates a rotation matrix
  5912. * @param yaw defines the yaw angle in radians (Y axis)
  5913. * @param pitch defines the pitch angle in radians (X axis)
  5914. * @param roll defines the roll angle in radians (X axis)
  5915. * @returns the new rotation matrix
  5916. */
  5917. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5918. var result = new Matrix();
  5919. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5920. return result;
  5921. };
  5922. /**
  5923. * Creates a rotation matrix and stores it in a given matrix
  5924. * @param yaw defines the yaw angle in radians (Y axis)
  5925. * @param pitch defines the pitch angle in radians (X axis)
  5926. * @param roll defines the roll angle in radians (X axis)
  5927. * @param result defines the target matrix
  5928. */
  5929. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5930. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5931. this._tempQuaternion.toRotationMatrix(result);
  5932. };
  5933. /**
  5934. * Creates a scaling matrix
  5935. * @param x defines the scale factor on X axis
  5936. * @param y defines the scale factor on Y axis
  5937. * @param z defines the scale factor on Z axis
  5938. * @returns the new matrix
  5939. */
  5940. Matrix.Scaling = function (x, y, z) {
  5941. var result = Matrix.Zero();
  5942. Matrix.ScalingToRef(x, y, z, result);
  5943. return result;
  5944. };
  5945. /**
  5946. * Creates a scaling matrix and stores it in a given matrix
  5947. * @param x defines the scale factor on X axis
  5948. * @param y defines the scale factor on Y axis
  5949. * @param z defines the scale factor on Z axis
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.ScalingToRef = function (x, y, z, result) {
  5953. result.m[0] = x;
  5954. result.m[1] = 0.0;
  5955. result.m[2] = 0.0;
  5956. result.m[3] = 0.0;
  5957. result.m[4] = 0.0;
  5958. result.m[5] = y;
  5959. result.m[6] = 0.0;
  5960. result.m[7] = 0.0;
  5961. result.m[8] = 0.0;
  5962. result.m[9] = 0.0;
  5963. result.m[10] = z;
  5964. result.m[11] = 0.0;
  5965. result.m[12] = 0.0;
  5966. result.m[13] = 0.0;
  5967. result.m[14] = 0.0;
  5968. result.m[15] = 1.0;
  5969. result._markAsUpdated();
  5970. };
  5971. /**
  5972. * Creates a translation matrix
  5973. * @param x defines the translation on X axis
  5974. * @param y defines the translation on Y axis
  5975. * @param z defines the translationon Z axis
  5976. * @returns the new matrix
  5977. */
  5978. Matrix.Translation = function (x, y, z) {
  5979. var result = Matrix.Identity();
  5980. Matrix.TranslationToRef(x, y, z, result);
  5981. return result;
  5982. };
  5983. /**
  5984. * Creates a translation matrix and stores it in a given matrix
  5985. * @param x defines the translation on X axis
  5986. * @param y defines the translation on Y axis
  5987. * @param z defines the translationon Z axis
  5988. * @param result defines the target matrix
  5989. */
  5990. Matrix.TranslationToRef = function (x, y, z, result) {
  5991. 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);
  5992. };
  5993. /**
  5994. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5995. * @param startValue defines the start value
  5996. * @param endValue defines the end value
  5997. * @param gradient defines the gradient factor
  5998. * @returns the new matrix
  5999. */
  6000. Matrix.Lerp = function (startValue, endValue, gradient) {
  6001. var result = Matrix.Zero();
  6002. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6003. return result;
  6004. };
  6005. /**
  6006. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6007. * @param startValue defines the start value
  6008. * @param endValue defines the end value
  6009. * @param gradient defines the gradient factor
  6010. * @param result defines the Matrix object where to store data
  6011. */
  6012. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6013. for (var index = 0; index < 16; index++) {
  6014. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6015. }
  6016. result._markAsUpdated();
  6017. };
  6018. /**
  6019. * Builds a new matrix whose values are computed by:
  6020. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6021. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6022. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6023. * @param startValue defines the first matrix
  6024. * @param endValue defines the second matrix
  6025. * @param gradient defines the gradient between the two matrices
  6026. * @returns the new matrix
  6027. */
  6028. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6029. var result = Matrix.Zero();
  6030. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6031. return result;
  6032. };
  6033. /**
  6034. * Update a matrix to values which are computed by:
  6035. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6036. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6037. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6038. * @param startValue defines the first matrix
  6039. * @param endValue defines the second matrix
  6040. * @param gradient defines the gradient between the two matrices
  6041. * @param result defines the target matrix
  6042. */
  6043. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6044. var startScale = MathTmp.Vector3[0];
  6045. var startRotation = MathTmp.Quaternion[0];
  6046. var startTranslation = MathTmp.Vector3[1];
  6047. startValue.decompose(startScale, startRotation, startTranslation);
  6048. var endScale = MathTmp.Vector3[2];
  6049. var endRotation = MathTmp.Quaternion[1];
  6050. var endTranslation = MathTmp.Vector3[3];
  6051. endValue.decompose(endScale, endRotation, endTranslation);
  6052. var resultScale = MathTmp.Vector3[4];
  6053. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6054. var resultRotation = MathTmp.Quaternion[2];
  6055. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6056. var resultTranslation = MathTmp.Vector3[5];
  6057. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6058. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6059. };
  6060. /**
  6061. * 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"
  6062. * This function works in left handed mode
  6063. * @param eye defines the final position of the entity
  6064. * @param target defines where the entity should look at
  6065. * @param up defines the up vector for the entity
  6066. * @returns the new matrix
  6067. */
  6068. Matrix.LookAtLH = function (eye, target, up) {
  6069. var result = Matrix.Zero();
  6070. Matrix.LookAtLHToRef(eye, target, up, result);
  6071. return result;
  6072. };
  6073. /**
  6074. * 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".
  6075. * This function works in left handed mode
  6076. * @param eye defines the final position of the entity
  6077. * @param target defines where the entity should look at
  6078. * @param up defines the up vector for the entity
  6079. * @param result defines the target matrix
  6080. */
  6081. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6082. // Z axis
  6083. target.subtractToRef(eye, this._zAxis);
  6084. this._zAxis.normalize();
  6085. // X axis
  6086. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6087. if (this._xAxis.lengthSquared() === 0) {
  6088. this._xAxis.x = 1.0;
  6089. }
  6090. else {
  6091. this._xAxis.normalize();
  6092. }
  6093. // Y axis
  6094. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6095. this._yAxis.normalize();
  6096. // Eye angles
  6097. var ex = -Vector3.Dot(this._xAxis, eye);
  6098. var ey = -Vector3.Dot(this._yAxis, eye);
  6099. var ez = -Vector3.Dot(this._zAxis, eye);
  6100. 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);
  6101. };
  6102. /**
  6103. * 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"
  6104. * This function works in right handed mode
  6105. * @param eye defines the final position of the entity
  6106. * @param target defines where the entity should look at
  6107. * @param up defines the up vector for the entity
  6108. * @returns the new matrix
  6109. */
  6110. Matrix.LookAtRH = function (eye, target, up) {
  6111. var result = Matrix.Zero();
  6112. Matrix.LookAtRHToRef(eye, target, up, result);
  6113. return result;
  6114. };
  6115. /**
  6116. * 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".
  6117. * This function works in right handed mode
  6118. * @param eye defines the final position of the entity
  6119. * @param target defines where the entity should look at
  6120. * @param up defines the up vector for the entity
  6121. * @param result defines the target matrix
  6122. */
  6123. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6124. // Z axis
  6125. eye.subtractToRef(target, this._zAxis);
  6126. this._zAxis.normalize();
  6127. // X axis
  6128. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6129. if (this._xAxis.lengthSquared() === 0) {
  6130. this._xAxis.x = 1.0;
  6131. }
  6132. else {
  6133. this._xAxis.normalize();
  6134. }
  6135. // Y axis
  6136. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6137. this._yAxis.normalize();
  6138. // Eye angles
  6139. var ex = -Vector3.Dot(this._xAxis, eye);
  6140. var ey = -Vector3.Dot(this._yAxis, eye);
  6141. var ez = -Vector3.Dot(this._zAxis, eye);
  6142. 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);
  6143. };
  6144. /**
  6145. * Create a left-handed orthographic projection matrix
  6146. * @param width defines the viewport width
  6147. * @param height defines the viewport height
  6148. * @param znear defines the near clip plane
  6149. * @param zfar defines the far clip plane
  6150. * @returns a new matrix as a left-handed orthographic projection matrix
  6151. */
  6152. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6153. var matrix = Matrix.Zero();
  6154. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6155. return matrix;
  6156. };
  6157. /**
  6158. * Store a left-handed orthographic projection to a given matrix
  6159. * @param width defines the viewport width
  6160. * @param height defines the viewport height
  6161. * @param znear defines the near clip plane
  6162. * @param zfar defines the far clip plane
  6163. * @param result defines the target matrix
  6164. */
  6165. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6166. var n = znear;
  6167. var f = zfar;
  6168. var a = 2.0 / width;
  6169. var b = 2.0 / height;
  6170. var c = 2.0 / (f - n);
  6171. var d = -(f + n) / (f - n);
  6172. 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);
  6173. };
  6174. /**
  6175. * Create a left-handed orthographic projection matrix
  6176. * @param left defines the viewport left coordinate
  6177. * @param right defines the viewport right coordinate
  6178. * @param bottom defines the viewport bottom coordinate
  6179. * @param top defines the viewport top coordinate
  6180. * @param znear defines the near clip plane
  6181. * @param zfar defines the far clip plane
  6182. * @returns a new matrix as a left-handed orthographic projection matrix
  6183. */
  6184. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6185. var matrix = Matrix.Zero();
  6186. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6187. return matrix;
  6188. };
  6189. /**
  6190. * Stores a left-handed orthographic projection into a given matrix
  6191. * @param left defines the viewport left coordinate
  6192. * @param right defines the viewport right coordinate
  6193. * @param bottom defines the viewport bottom coordinate
  6194. * @param top defines the viewport top coordinate
  6195. * @param znear defines the near clip plane
  6196. * @param zfar defines the far clip plane
  6197. * @param result defines the target matrix
  6198. */
  6199. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6200. var n = znear;
  6201. var f = zfar;
  6202. var a = 2.0 / (right - left);
  6203. var b = 2.0 / (top - bottom);
  6204. var c = 2.0 / (f - n);
  6205. var d = -(f + n) / (f - n);
  6206. var i0 = (left + right) / (left - right);
  6207. var i1 = (top + bottom) / (bottom - top);
  6208. 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);
  6209. };
  6210. /**
  6211. * Creates a right-handed orthographic projection matrix
  6212. * @param left defines the viewport left coordinate
  6213. * @param right defines the viewport right coordinate
  6214. * @param bottom defines the viewport bottom coordinate
  6215. * @param top defines the viewport top coordinate
  6216. * @param znear defines the near clip plane
  6217. * @param zfar defines the far clip plane
  6218. * @returns a new matrix as a right-handed orthographic projection matrix
  6219. */
  6220. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6221. var matrix = Matrix.Zero();
  6222. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6223. return matrix;
  6224. };
  6225. /**
  6226. * Stores a right-handed orthographic projection into a given matrix
  6227. * @param left defines the viewport left coordinate
  6228. * @param right defines the viewport right coordinate
  6229. * @param bottom defines the viewport bottom coordinate
  6230. * @param top defines the viewport top coordinate
  6231. * @param znear defines the near clip plane
  6232. * @param zfar defines the far clip plane
  6233. * @param result defines the target matrix
  6234. */
  6235. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6236. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6237. result.m[10] *= -1.0;
  6238. };
  6239. /**
  6240. * Creates a left-handed perspective projection matrix
  6241. * @param width defines the viewport width
  6242. * @param height defines the viewport height
  6243. * @param znear defines the near clip plane
  6244. * @param zfar defines the far clip plane
  6245. * @returns a new matrix as a left-handed perspective projection matrix
  6246. */
  6247. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6248. var matrix = Matrix.Zero();
  6249. var n = znear;
  6250. var f = zfar;
  6251. var a = 2.0 * n / width;
  6252. var b = 2.0 * n / height;
  6253. var c = (f + n) / (f - n);
  6254. var d = -2.0 * f * n / (f - n);
  6255. 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);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Creates a left-handed perspective projection matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @returns a new matrix as a left-handed perspective projection matrix
  6265. */
  6266. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6267. var matrix = Matrix.Zero();
  6268. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6269. return matrix;
  6270. };
  6271. /**
  6272. * Stores a left-handed perspective projection into a given matrix
  6273. * @param fov defines the horizontal field of view
  6274. * @param aspect defines the aspect ratio
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @param result defines the target matrix
  6278. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6279. */
  6280. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6281. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6282. var n = znear;
  6283. var f = zfar;
  6284. var t = 1.0 / (Math.tan(fov * 0.5));
  6285. var a = isVerticalFovFixed ? (t / aspect) : t;
  6286. var b = isVerticalFovFixed ? t : (t * aspect);
  6287. var c = (f + n) / (f - n);
  6288. var d = -2.0 * f * n / (f - n);
  6289. 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);
  6290. };
  6291. /**
  6292. * Creates a right-handed perspective projection matrix
  6293. * @param fov defines the horizontal field of view
  6294. * @param aspect defines the aspect ratio
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @returns a new matrix as a right-handed perspective projection matrix
  6298. */
  6299. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6300. var matrix = Matrix.Zero();
  6301. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6302. return matrix;
  6303. };
  6304. /**
  6305. * Stores a right-handed perspective projection into a given matrix
  6306. * @param fov defines the horizontal field of view
  6307. * @param aspect defines the aspect ratio
  6308. * @param znear defines the near clip plane
  6309. * @param zfar defines the far clip plane
  6310. * @param result defines the target matrix
  6311. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6312. */
  6313. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6314. //alternatively this could be expressed as:
  6315. // m = PerspectiveFovLHToRef
  6316. // m[10] *= -1.0;
  6317. // m[11] *= -1.0;
  6318. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6319. var n = znear;
  6320. var f = zfar;
  6321. var t = 1.0 / (Math.tan(fov * 0.5));
  6322. var a = isVerticalFovFixed ? (t / aspect) : t;
  6323. var b = isVerticalFovFixed ? t : (t * aspect);
  6324. var c = -(f + n) / (f - n);
  6325. var d = -2 * f * n / (f - n);
  6326. 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);
  6327. };
  6328. /**
  6329. * Stores a perspective projection for WebVR info a given matrix
  6330. * @param fov defines the field of view
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6335. */
  6336. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6337. if (rightHanded === void 0) { rightHanded = false; }
  6338. var rightHandedFactor = rightHanded ? -1 : 1;
  6339. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6340. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6341. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6342. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6343. var xScale = 2.0 / (leftTan + rightTan);
  6344. var yScale = 2.0 / (upTan + downTan);
  6345. result.m[0] = xScale;
  6346. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6347. result.m[5] = yScale;
  6348. result.m[6] = result.m[7] = 0.0;
  6349. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6350. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6351. result.m[10] = -zfar / (znear - zfar);
  6352. result.m[11] = 1.0 * rightHandedFactor;
  6353. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6354. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6355. result._markAsUpdated();
  6356. };
  6357. /**
  6358. * Computes a complete transformation matrix
  6359. * @param viewport defines the viewport to use
  6360. * @param world defines the world matrix
  6361. * @param view defines the view matrix
  6362. * @param projection defines the projection matrix
  6363. * @param zmin defines the near clip plane
  6364. * @param zmax defines the far clip plane
  6365. * @returns the transformation matrix
  6366. */
  6367. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6368. var cw = viewport.width;
  6369. var ch = viewport.height;
  6370. var cx = viewport.x;
  6371. var cy = viewport.y;
  6372. 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);
  6373. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6374. };
  6375. /**
  6376. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6377. * @param matrix defines the matrix to use
  6378. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6379. */
  6380. Matrix.GetAsMatrix2x2 = function (matrix) {
  6381. return new Float32Array([
  6382. matrix.m[0], matrix.m[1],
  6383. matrix.m[4], matrix.m[5]
  6384. ]);
  6385. };
  6386. /**
  6387. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6388. * @param matrix defines the matrix to use
  6389. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6390. */
  6391. Matrix.GetAsMatrix3x3 = function (matrix) {
  6392. return new Float32Array([
  6393. matrix.m[0], matrix.m[1], matrix.m[2],
  6394. matrix.m[4], matrix.m[5], matrix.m[6],
  6395. matrix.m[8], matrix.m[9], matrix.m[10]
  6396. ]);
  6397. };
  6398. /**
  6399. * Compute the transpose of a given matrix
  6400. * @param matrix defines the matrix to transpose
  6401. * @returns the new matrix
  6402. */
  6403. Matrix.Transpose = function (matrix) {
  6404. var result = new Matrix();
  6405. Matrix.TransposeToRef(matrix, result);
  6406. return result;
  6407. };
  6408. /**
  6409. * Compute the transpose of a matrix and store it in a target matrix
  6410. * @param matrix defines the matrix to transpose
  6411. * @param result defines the target matrix
  6412. */
  6413. Matrix.TransposeToRef = function (matrix, result) {
  6414. result.m[0] = matrix.m[0];
  6415. result.m[1] = matrix.m[4];
  6416. result.m[2] = matrix.m[8];
  6417. result.m[3] = matrix.m[12];
  6418. result.m[4] = matrix.m[1];
  6419. result.m[5] = matrix.m[5];
  6420. result.m[6] = matrix.m[9];
  6421. result.m[7] = matrix.m[13];
  6422. result.m[8] = matrix.m[2];
  6423. result.m[9] = matrix.m[6];
  6424. result.m[10] = matrix.m[10];
  6425. result.m[11] = matrix.m[14];
  6426. result.m[12] = matrix.m[3];
  6427. result.m[13] = matrix.m[7];
  6428. result.m[14] = matrix.m[11];
  6429. result.m[15] = matrix.m[15];
  6430. };
  6431. /**
  6432. * Computes a reflection matrix from a plane
  6433. * @param plane defines the reflection plane
  6434. * @returns a new matrix
  6435. */
  6436. Matrix.Reflection = function (plane) {
  6437. var matrix = new Matrix();
  6438. Matrix.ReflectionToRef(plane, matrix);
  6439. return matrix;
  6440. };
  6441. /**
  6442. * Computes a reflection matrix from a plane
  6443. * @param plane defines the reflection plane
  6444. * @param result defines the target matrix
  6445. */
  6446. Matrix.ReflectionToRef = function (plane, result) {
  6447. plane.normalize();
  6448. var x = plane.normal.x;
  6449. var y = plane.normal.y;
  6450. var z = plane.normal.z;
  6451. var temp = -2 * x;
  6452. var temp2 = -2 * y;
  6453. var temp3 = -2 * z;
  6454. result.m[0] = (temp * x) + 1;
  6455. result.m[1] = temp2 * x;
  6456. result.m[2] = temp3 * x;
  6457. result.m[3] = 0.0;
  6458. result.m[4] = temp * y;
  6459. result.m[5] = (temp2 * y) + 1;
  6460. result.m[6] = temp3 * y;
  6461. result.m[7] = 0.0;
  6462. result.m[8] = temp * z;
  6463. result.m[9] = temp2 * z;
  6464. result.m[10] = (temp3 * z) + 1;
  6465. result.m[11] = 0.0;
  6466. result.m[12] = temp * plane.d;
  6467. result.m[13] = temp2 * plane.d;
  6468. result.m[14] = temp3 * plane.d;
  6469. result.m[15] = 1.0;
  6470. result._markAsUpdated();
  6471. };
  6472. /**
  6473. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6474. * @param xaxis defines the value of the 1st axis
  6475. * @param yaxis defines the value of the 2nd axis
  6476. * @param zaxis defines the value of the 3rd axis
  6477. * @param result defines the target matrix
  6478. */
  6479. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6480. result.m[0] = xaxis.x;
  6481. result.m[1] = xaxis.y;
  6482. result.m[2] = xaxis.z;
  6483. result.m[3] = 0.0;
  6484. result.m[4] = yaxis.x;
  6485. result.m[5] = yaxis.y;
  6486. result.m[6] = yaxis.z;
  6487. result.m[7] = 0.0;
  6488. result.m[8] = zaxis.x;
  6489. result.m[9] = zaxis.y;
  6490. result.m[10] = zaxis.z;
  6491. result.m[11] = 0.0;
  6492. result.m[12] = 0.0;
  6493. result.m[13] = 0.0;
  6494. result.m[14] = 0.0;
  6495. result.m[15] = 1.0;
  6496. result._markAsUpdated();
  6497. };
  6498. /**
  6499. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6500. * @param quat defines the quaternion to use
  6501. * @param result defines the target matrix
  6502. */
  6503. Matrix.FromQuaternionToRef = function (quat, result) {
  6504. var xx = quat.x * quat.x;
  6505. var yy = quat.y * quat.y;
  6506. var zz = quat.z * quat.z;
  6507. var xy = quat.x * quat.y;
  6508. var zw = quat.z * quat.w;
  6509. var zx = quat.z * quat.x;
  6510. var yw = quat.y * quat.w;
  6511. var yz = quat.y * quat.z;
  6512. var xw = quat.x * quat.w;
  6513. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6514. result.m[1] = 2.0 * (xy + zw);
  6515. result.m[2] = 2.0 * (zx - yw);
  6516. result.m[3] = 0.0;
  6517. result.m[4] = 2.0 * (xy - zw);
  6518. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6519. result.m[6] = 2.0 * (yz + xw);
  6520. result.m[7] = 0.0;
  6521. result.m[8] = 2.0 * (zx + yw);
  6522. result.m[9] = 2.0 * (yz - xw);
  6523. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6524. result.m[11] = 0.0;
  6525. result.m[12] = 0.0;
  6526. result.m[13] = 0.0;
  6527. result.m[14] = 0.0;
  6528. result.m[15] = 1.0;
  6529. result._markAsUpdated();
  6530. };
  6531. Matrix._tempQuaternion = new Quaternion();
  6532. Matrix._xAxis = Vector3.Zero();
  6533. Matrix._yAxis = Vector3.Zero();
  6534. Matrix._zAxis = Vector3.Zero();
  6535. Matrix._updateFlagSeed = 0;
  6536. Matrix._identityReadOnly = Matrix.Identity();
  6537. return Matrix;
  6538. }());
  6539. BABYLON.Matrix = Matrix;
  6540. var Plane = /** @class */ (function () {
  6541. /**
  6542. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6543. */
  6544. function Plane(a, b, c, d) {
  6545. this.normal = new Vector3(a, b, c);
  6546. this.d = d;
  6547. }
  6548. /**
  6549. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6550. */
  6551. Plane.prototype.asArray = function () {
  6552. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6553. };
  6554. // Methods
  6555. /**
  6556. * Returns a new plane copied from the current Plane.
  6557. */
  6558. Plane.prototype.clone = function () {
  6559. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6560. };
  6561. /**
  6562. * Returns the string "Plane".
  6563. */
  6564. Plane.prototype.getClassName = function () {
  6565. return "Plane";
  6566. };
  6567. /**
  6568. * Returns the Plane hash code.
  6569. */
  6570. Plane.prototype.getHashCode = function () {
  6571. var hash = this.normal.getHashCode();
  6572. hash = (hash * 397) ^ (this.d || 0);
  6573. return hash;
  6574. };
  6575. /**
  6576. * Normalize the current Plane in place.
  6577. * Returns the updated Plane.
  6578. */
  6579. Plane.prototype.normalize = function () {
  6580. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6581. var magnitude = 0.0;
  6582. if (norm !== 0) {
  6583. magnitude = 1.0 / norm;
  6584. }
  6585. this.normal.x *= magnitude;
  6586. this.normal.y *= magnitude;
  6587. this.normal.z *= magnitude;
  6588. this.d *= magnitude;
  6589. return this;
  6590. };
  6591. /**
  6592. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6593. */
  6594. Plane.prototype.transform = function (transformation) {
  6595. var transposedMatrix = Matrix.Transpose(transformation);
  6596. var x = this.normal.x;
  6597. var y = this.normal.y;
  6598. var z = this.normal.z;
  6599. var d = this.d;
  6600. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6601. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6602. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6603. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6604. return new Plane(normalX, normalY, normalZ, finalD);
  6605. };
  6606. /**
  6607. * Returns the dot product (float) of the point coordinates and the plane normal.
  6608. */
  6609. Plane.prototype.dotCoordinate = function (point) {
  6610. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6611. };
  6612. /**
  6613. * Updates the current Plane from the plane defined by the three given points.
  6614. * Returns the updated Plane.
  6615. */
  6616. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6617. var x1 = point2.x - point1.x;
  6618. var y1 = point2.y - point1.y;
  6619. var z1 = point2.z - point1.z;
  6620. var x2 = point3.x - point1.x;
  6621. var y2 = point3.y - point1.y;
  6622. var z2 = point3.z - point1.z;
  6623. var yz = (y1 * z2) - (z1 * y2);
  6624. var xz = (z1 * x2) - (x1 * z2);
  6625. var xy = (x1 * y2) - (y1 * x2);
  6626. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6627. var invPyth;
  6628. if (pyth !== 0) {
  6629. invPyth = 1.0 / pyth;
  6630. }
  6631. else {
  6632. invPyth = 0.0;
  6633. }
  6634. this.normal.x = yz * invPyth;
  6635. this.normal.y = xz * invPyth;
  6636. this.normal.z = xy * invPyth;
  6637. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6638. return this;
  6639. };
  6640. /**
  6641. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6642. */
  6643. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6644. var dot = Vector3.Dot(this.normal, direction);
  6645. return (dot <= epsilon);
  6646. };
  6647. /**
  6648. * Returns the signed distance (float) from the given point to the Plane.
  6649. */
  6650. Plane.prototype.signedDistanceTo = function (point) {
  6651. return Vector3.Dot(point, this.normal) + this.d;
  6652. };
  6653. // Statics
  6654. /**
  6655. * Returns a new Plane from the given array.
  6656. */
  6657. Plane.FromArray = function (array) {
  6658. return new Plane(array[0], array[1], array[2], array[3]);
  6659. };
  6660. /**
  6661. * Returns a new Plane defined by the three given points.
  6662. */
  6663. Plane.FromPoints = function (point1, point2, point3) {
  6664. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6665. result.copyFromPoints(point1, point2, point3);
  6666. return result;
  6667. };
  6668. /**
  6669. * Returns a new Plane the normal vector to this plane at the given origin point.
  6670. * Note : the vector "normal" is updated because normalized.
  6671. */
  6672. Plane.FromPositionAndNormal = function (origin, normal) {
  6673. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6674. normal.normalize();
  6675. result.normal = normal;
  6676. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6677. return result;
  6678. };
  6679. /**
  6680. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6681. */
  6682. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6683. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6684. return Vector3.Dot(point, normal) + d;
  6685. };
  6686. return Plane;
  6687. }());
  6688. BABYLON.Plane = Plane;
  6689. var Viewport = /** @class */ (function () {
  6690. /**
  6691. * Creates a Viewport object located at (x, y) and sized (width, height).
  6692. */
  6693. function Viewport(x, y, width, height) {
  6694. this.x = x;
  6695. this.y = y;
  6696. this.width = width;
  6697. this.height = height;
  6698. }
  6699. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6700. if (renderWidthOrEngine.getRenderWidth) {
  6701. var engine = renderWidthOrEngine;
  6702. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6703. }
  6704. var renderWidth = renderWidthOrEngine;
  6705. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6706. };
  6707. /**
  6708. * Returns a new Viewport copied from the current one.
  6709. */
  6710. Viewport.prototype.clone = function () {
  6711. return new Viewport(this.x, this.y, this.width, this.height);
  6712. };
  6713. return Viewport;
  6714. }());
  6715. BABYLON.Viewport = Viewport;
  6716. var Frustum = /** @class */ (function () {
  6717. function Frustum() {
  6718. }
  6719. /**
  6720. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6721. */
  6722. Frustum.GetPlanes = function (transform) {
  6723. var frustumPlanes = [];
  6724. for (var index = 0; index < 6; index++) {
  6725. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6726. }
  6727. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6728. return frustumPlanes;
  6729. };
  6730. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6731. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6732. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6733. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6734. frustumPlane.d = transform.m[15] + transform.m[14];
  6735. frustumPlane.normalize();
  6736. };
  6737. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6738. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6739. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6740. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6741. frustumPlane.d = transform.m[15] - transform.m[14];
  6742. frustumPlane.normalize();
  6743. };
  6744. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6745. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6746. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6747. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6748. frustumPlane.d = transform.m[15] + transform.m[12];
  6749. frustumPlane.normalize();
  6750. };
  6751. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6752. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6753. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6754. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6755. frustumPlane.d = transform.m[15] - transform.m[12];
  6756. frustumPlane.normalize();
  6757. };
  6758. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6759. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6760. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6761. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6762. frustumPlane.d = transform.m[15] - transform.m[13];
  6763. frustumPlane.normalize();
  6764. };
  6765. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6766. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6767. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6768. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6769. frustumPlane.d = transform.m[15] + transform.m[13];
  6770. frustumPlane.normalize();
  6771. };
  6772. /**
  6773. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6774. */
  6775. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6776. // Near
  6777. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6778. // Far
  6779. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6780. // Left
  6781. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6782. // Right
  6783. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6784. // Top
  6785. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6786. // Bottom
  6787. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6788. };
  6789. return Frustum;
  6790. }());
  6791. BABYLON.Frustum = Frustum;
  6792. /** Defines supported spaces */
  6793. var Space;
  6794. (function (Space) {
  6795. /** Local (object) space */
  6796. Space[Space["LOCAL"] = 0] = "LOCAL";
  6797. /** World space */
  6798. Space[Space["WORLD"] = 1] = "WORLD";
  6799. /** Bone space */
  6800. Space[Space["BONE"] = 2] = "BONE";
  6801. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6802. /** Defines the 3 main axes */
  6803. var Axis = /** @class */ (function () {
  6804. function Axis() {
  6805. }
  6806. /** X axis */
  6807. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6808. /** Y axis */
  6809. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6810. /** Z axis */
  6811. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6812. return Axis;
  6813. }());
  6814. BABYLON.Axis = Axis;
  6815. ;
  6816. var BezierCurve = /** @class */ (function () {
  6817. function BezierCurve() {
  6818. }
  6819. /**
  6820. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6821. */
  6822. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6823. // Extract X (which is equal to time here)
  6824. var f0 = 1 - 3 * x2 + 3 * x1;
  6825. var f1 = 3 * x2 - 6 * x1;
  6826. var f2 = 3 * x1;
  6827. var refinedT = t;
  6828. for (var i = 0; i < 5; i++) {
  6829. var refinedT2 = refinedT * refinedT;
  6830. var refinedT3 = refinedT2 * refinedT;
  6831. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6832. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6833. refinedT -= (x - t) * slope;
  6834. refinedT = Math.min(1, Math.max(0, refinedT));
  6835. }
  6836. // Resolve cubic bezier for the given x
  6837. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6838. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6839. Math.pow(refinedT, 3);
  6840. };
  6841. return BezierCurve;
  6842. }());
  6843. BABYLON.BezierCurve = BezierCurve;
  6844. /**
  6845. * Defines potential orientation for back face culling
  6846. */
  6847. var Orientation;
  6848. (function (Orientation) {
  6849. /**
  6850. * Clockwise
  6851. */
  6852. Orientation[Orientation["CW"] = 0] = "CW";
  6853. /** Counter clockwise */
  6854. Orientation[Orientation["CCW"] = 1] = "CCW";
  6855. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6856. /**
  6857. * Defines angle representation
  6858. */
  6859. var Angle = /** @class */ (function () {
  6860. /**
  6861. * Creates an Angle object of "radians" radians (float).
  6862. */
  6863. function Angle(radians) {
  6864. this._radians = radians;
  6865. if (this._radians < 0.0)
  6866. this._radians += (2.0 * Math.PI);
  6867. }
  6868. /**
  6869. * Get value in degrees
  6870. * @returns the Angle value in degrees (float)
  6871. */
  6872. Angle.prototype.degrees = function () {
  6873. return this._radians * 180.0 / Math.PI;
  6874. };
  6875. /**
  6876. * Get value in radians
  6877. * @returns the Angle value in radians (float)
  6878. */
  6879. Angle.prototype.radians = function () {
  6880. return this._radians;
  6881. };
  6882. /**
  6883. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6884. * @param a defines first vector
  6885. * @param b defines second vector
  6886. * @returns a new Angle
  6887. */
  6888. Angle.BetweenTwoPoints = function (a, b) {
  6889. var delta = b.subtract(a);
  6890. var theta = Math.atan2(delta.y, delta.x);
  6891. return new Angle(theta);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in radians
  6895. * @param radians defines the angle value in radians
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromRadians = function (radians) {
  6899. return new Angle(radians);
  6900. };
  6901. /**
  6902. * Gets a new Angle object from the given float in degrees
  6903. * @param degrees defines the angle value in degrees
  6904. * @returns a new Angle
  6905. */
  6906. Angle.FromDegrees = function (degrees) {
  6907. return new Angle(degrees * Math.PI / 180.0);
  6908. };
  6909. return Angle;
  6910. }());
  6911. BABYLON.Angle = Angle;
  6912. var Arc2 = /** @class */ (function () {
  6913. /**
  6914. * Creates an Arc object from the three given points : start, middle and end.
  6915. */
  6916. function Arc2(startPoint, midPoint, endPoint) {
  6917. this.startPoint = startPoint;
  6918. this.midPoint = midPoint;
  6919. this.endPoint = endPoint;
  6920. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6921. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6922. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6923. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6924. 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);
  6925. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6926. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6927. var a1 = this.startAngle.degrees();
  6928. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6929. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6930. // angles correction
  6931. if (a2 - a1 > +180.0)
  6932. a2 -= 360.0;
  6933. if (a2 - a1 < -180.0)
  6934. a2 += 360.0;
  6935. if (a3 - a2 > +180.0)
  6936. a3 -= 360.0;
  6937. if (a3 - a2 < -180.0)
  6938. a3 += 360.0;
  6939. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6940. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6941. }
  6942. return Arc2;
  6943. }());
  6944. BABYLON.Arc2 = Arc2;
  6945. var Path2 = /** @class */ (function () {
  6946. /**
  6947. * Creates a Path2 object from the starting 2D coordinates x and y.
  6948. */
  6949. function Path2(x, y) {
  6950. this._points = new Array();
  6951. this._length = 0.0;
  6952. this.closed = false;
  6953. this._points.push(new Vector2(x, y));
  6954. }
  6955. /**
  6956. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6957. * Returns the updated Path2.
  6958. */
  6959. Path2.prototype.addLineTo = function (x, y) {
  6960. if (this.closed) {
  6961. return this;
  6962. }
  6963. var newPoint = new Vector2(x, y);
  6964. var previousPoint = this._points[this._points.length - 1];
  6965. this._points.push(newPoint);
  6966. this._length += newPoint.subtract(previousPoint).length();
  6967. return this;
  6968. };
  6969. /**
  6970. * 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.
  6971. * Returns the updated Path2.
  6972. */
  6973. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6974. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6975. if (this.closed) {
  6976. return this;
  6977. }
  6978. var startPoint = this._points[this._points.length - 1];
  6979. var midPoint = new Vector2(midX, midY);
  6980. var endPoint = new Vector2(endX, endY);
  6981. var arc = new Arc2(startPoint, midPoint, endPoint);
  6982. var increment = arc.angle.radians() / numberOfSegments;
  6983. if (arc.orientation === Orientation.CW)
  6984. increment *= -1;
  6985. var currentAngle = arc.startAngle.radians() + increment;
  6986. for (var i = 0; i < numberOfSegments; i++) {
  6987. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6988. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6989. this.addLineTo(x, y);
  6990. currentAngle += increment;
  6991. }
  6992. return this;
  6993. };
  6994. /**
  6995. * Closes the Path2.
  6996. * Returns the Path2.
  6997. */
  6998. Path2.prototype.close = function () {
  6999. this.closed = true;
  7000. return this;
  7001. };
  7002. /**
  7003. * Returns the Path2 total length (float).
  7004. */
  7005. Path2.prototype.length = function () {
  7006. var result = this._length;
  7007. if (!this.closed) {
  7008. var lastPoint = this._points[this._points.length - 1];
  7009. var firstPoint = this._points[0];
  7010. result += (firstPoint.subtract(lastPoint).length());
  7011. }
  7012. return result;
  7013. };
  7014. /**
  7015. * Returns the Path2 internal array of points.
  7016. */
  7017. Path2.prototype.getPoints = function () {
  7018. return this._points;
  7019. };
  7020. /**
  7021. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7022. */
  7023. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7024. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7025. return Vector2.Zero();
  7026. }
  7027. var lengthPosition = normalizedLengthPosition * this.length();
  7028. var previousOffset = 0;
  7029. for (var i = 0; i < this._points.length; i++) {
  7030. var j = (i + 1) % this._points.length;
  7031. var a = this._points[i];
  7032. var b = this._points[j];
  7033. var bToA = b.subtract(a);
  7034. var nextOffset = (bToA.length() + previousOffset);
  7035. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7036. var dir = bToA.normalize();
  7037. var localOffset = lengthPosition - previousOffset;
  7038. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7039. }
  7040. previousOffset = nextOffset;
  7041. }
  7042. return Vector2.Zero();
  7043. };
  7044. /**
  7045. * Returns a new Path2 starting at the coordinates (x, y).
  7046. */
  7047. Path2.StartingAt = function (x, y) {
  7048. return new Path2(x, y);
  7049. };
  7050. return Path2;
  7051. }());
  7052. BABYLON.Path2 = Path2;
  7053. var Path3D = /** @class */ (function () {
  7054. /**
  7055. * new Path3D(path, normal, raw)
  7056. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7057. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7058. * path : an array of Vector3, the curve axis of the Path3D
  7059. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7060. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7061. */
  7062. function Path3D(path, firstNormal, raw) {
  7063. if (firstNormal === void 0) { firstNormal = null; }
  7064. this.path = path;
  7065. this._curve = new Array();
  7066. this._distances = new Array();
  7067. this._tangents = new Array();
  7068. this._normals = new Array();
  7069. this._binormals = new Array();
  7070. for (var p = 0; p < path.length; p++) {
  7071. this._curve[p] = path[p].clone(); // hard copy
  7072. }
  7073. this._raw = raw || false;
  7074. this._compute(firstNormal);
  7075. }
  7076. /**
  7077. * Returns the Path3D array of successive Vector3 designing its curve.
  7078. */
  7079. Path3D.prototype.getCurve = function () {
  7080. return this._curve;
  7081. };
  7082. /**
  7083. * Returns an array populated with tangent vectors on each Path3D curve point.
  7084. */
  7085. Path3D.prototype.getTangents = function () {
  7086. return this._tangents;
  7087. };
  7088. /**
  7089. * Returns an array populated with normal vectors on each Path3D curve point.
  7090. */
  7091. Path3D.prototype.getNormals = function () {
  7092. return this._normals;
  7093. };
  7094. /**
  7095. * Returns an array populated with binormal vectors on each Path3D curve point.
  7096. */
  7097. Path3D.prototype.getBinormals = function () {
  7098. return this._binormals;
  7099. };
  7100. /**
  7101. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7102. */
  7103. Path3D.prototype.getDistances = function () {
  7104. return this._distances;
  7105. };
  7106. /**
  7107. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7108. * Returns the same object updated.
  7109. */
  7110. Path3D.prototype.update = function (path, firstNormal) {
  7111. if (firstNormal === void 0) { firstNormal = null; }
  7112. for (var p = 0; p < path.length; p++) {
  7113. this._curve[p].x = path[p].x;
  7114. this._curve[p].y = path[p].y;
  7115. this._curve[p].z = path[p].z;
  7116. }
  7117. this._compute(firstNormal);
  7118. return this;
  7119. };
  7120. // private function compute() : computes tangents, normals and binormals
  7121. Path3D.prototype._compute = function (firstNormal) {
  7122. var l = this._curve.length;
  7123. // first and last tangents
  7124. this._tangents[0] = this._getFirstNonNullVector(0);
  7125. if (!this._raw) {
  7126. this._tangents[0].normalize();
  7127. }
  7128. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7129. if (!this._raw) {
  7130. this._tangents[l - 1].normalize();
  7131. }
  7132. // normals and binormals at first point : arbitrary vector with _normalVector()
  7133. var tg0 = this._tangents[0];
  7134. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7135. this._normals[0] = pp0;
  7136. if (!this._raw) {
  7137. this._normals[0].normalize();
  7138. }
  7139. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7140. if (!this._raw) {
  7141. this._binormals[0].normalize();
  7142. }
  7143. this._distances[0] = 0.0;
  7144. // normals and binormals : next points
  7145. var prev; // previous vector (segment)
  7146. var cur; // current vector (segment)
  7147. var curTang; // current tangent
  7148. // previous normal
  7149. var prevBinor; // previous binormal
  7150. for (var i = 1; i < l; i++) {
  7151. // tangents
  7152. prev = this._getLastNonNullVector(i);
  7153. if (i < l - 1) {
  7154. cur = this._getFirstNonNullVector(i);
  7155. this._tangents[i] = prev.add(cur);
  7156. this._tangents[i].normalize();
  7157. }
  7158. this._distances[i] = this._distances[i - 1] + prev.length();
  7159. // normals and binormals
  7160. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7161. curTang = this._tangents[i];
  7162. prevBinor = this._binormals[i - 1];
  7163. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7164. if (!this._raw) {
  7165. this._normals[i].normalize();
  7166. }
  7167. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7168. if (!this._raw) {
  7169. this._binormals[i].normalize();
  7170. }
  7171. }
  7172. };
  7173. // private function getFirstNonNullVector(index)
  7174. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7175. Path3D.prototype._getFirstNonNullVector = function (index) {
  7176. var i = 1;
  7177. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7178. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7179. i++;
  7180. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7181. }
  7182. return nNVector;
  7183. };
  7184. // private function getLastNonNullVector(index)
  7185. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7186. Path3D.prototype._getLastNonNullVector = function (index) {
  7187. var i = 1;
  7188. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7189. while (nLVector.length() === 0 && index > i + 1) {
  7190. i++;
  7191. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7192. }
  7193. return nLVector;
  7194. };
  7195. // private function normalVector(v0, vt, va) :
  7196. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7197. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7198. Path3D.prototype._normalVector = function (v0, vt, va) {
  7199. var normal0;
  7200. var tgl = vt.length();
  7201. if (tgl === 0.0) {
  7202. tgl = 1.0;
  7203. }
  7204. if (va === undefined || va === null) {
  7205. var point;
  7206. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7207. point = new Vector3(0.0, -1.0, 0.0);
  7208. }
  7209. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7210. point = new Vector3(1.0, 0.0, 0.0);
  7211. }
  7212. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7213. point = new Vector3(0.0, 0.0, 1.0);
  7214. }
  7215. else {
  7216. point = Vector3.Zero();
  7217. }
  7218. normal0 = Vector3.Cross(vt, point);
  7219. }
  7220. else {
  7221. normal0 = Vector3.Cross(vt, va);
  7222. Vector3.CrossToRef(normal0, vt, normal0);
  7223. }
  7224. normal0.normalize();
  7225. return normal0;
  7226. };
  7227. return Path3D;
  7228. }());
  7229. BABYLON.Path3D = Path3D;
  7230. var Curve3 = /** @class */ (function () {
  7231. /**
  7232. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7233. * A Curve3 is designed from a series of successive Vector3.
  7234. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7235. */
  7236. function Curve3(points) {
  7237. this._length = 0.0;
  7238. this._points = points;
  7239. this._length = this._computeLength(points);
  7240. }
  7241. /**
  7242. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7243. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7244. * @param v1 (Vector3) the control point
  7245. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7246. * @param nbPoints (integer) the wanted number of points in the curve
  7247. */
  7248. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7249. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7250. var bez = new Array();
  7251. var equation = function (t, val0, val1, val2) {
  7252. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7253. return res;
  7254. };
  7255. for (var i = 0; i <= nbPoints; i++) {
  7256. 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)));
  7257. }
  7258. return new Curve3(bez);
  7259. };
  7260. /**
  7261. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7262. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7263. * @param v1 (Vector3) the first control point
  7264. * @param v2 (Vector3) the second control point
  7265. * @param v3 (Vector3) the end point of the Cubic Bezier
  7266. * @param nbPoints (integer) the wanted number of points in the curve
  7267. */
  7268. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7269. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7270. var bez = new Array();
  7271. var equation = function (t, val0, val1, val2, val3) {
  7272. 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;
  7273. return res;
  7274. };
  7275. for (var i = 0; i <= nbPoints; i++) {
  7276. 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)));
  7277. }
  7278. return new Curve3(bez);
  7279. };
  7280. /**
  7281. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7282. * @param p1 (Vector3) the origin point of the Hermite Spline
  7283. * @param t1 (Vector3) the tangent vector at the origin point
  7284. * @param p2 (Vector3) the end point of the Hermite Spline
  7285. * @param t2 (Vector3) the tangent vector at the end point
  7286. * @param nbPoints (integer) the wanted number of points in the curve
  7287. */
  7288. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7289. var hermite = new Array();
  7290. var step = 1.0 / nbPoints;
  7291. for (var i = 0; i <= nbPoints; i++) {
  7292. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7293. }
  7294. return new Curve3(hermite);
  7295. };
  7296. /**
  7297. * Returns a Curve3 object along a CatmullRom Spline curve :
  7298. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7299. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7300. */
  7301. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7302. var totalPoints = new Array();
  7303. totalPoints.push(points[0].clone());
  7304. Array.prototype.push.apply(totalPoints, points);
  7305. totalPoints.push(points[points.length - 1].clone());
  7306. var catmullRom = new Array();
  7307. var step = 1.0 / nbPoints;
  7308. var amount = 0.0;
  7309. for (var i = 0; i < totalPoints.length - 3; i++) {
  7310. amount = 0;
  7311. for (var c = 0; c < nbPoints; c++) {
  7312. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7313. amount += step;
  7314. }
  7315. }
  7316. i--;
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. return new Curve3(catmullRom);
  7319. };
  7320. /**
  7321. * Returns the Curve3 stored array of successive Vector3
  7322. */
  7323. Curve3.prototype.getPoints = function () {
  7324. return this._points;
  7325. };
  7326. /**
  7327. * Returns the computed length (float) of the curve.
  7328. */
  7329. Curve3.prototype.length = function () {
  7330. return this._length;
  7331. };
  7332. /**
  7333. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7334. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7335. * curveA and curveB keep unchanged.
  7336. */
  7337. Curve3.prototype.continue = function (curve) {
  7338. var lastPoint = this._points[this._points.length - 1];
  7339. var continuedPoints = this._points.slice();
  7340. var curvePoints = curve.getPoints();
  7341. for (var i = 1; i < curvePoints.length; i++) {
  7342. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7343. }
  7344. var continuedCurve = new Curve3(continuedPoints);
  7345. return continuedCurve;
  7346. };
  7347. Curve3.prototype._computeLength = function (path) {
  7348. var l = 0;
  7349. for (var i = 1; i < path.length; i++) {
  7350. l += (path[i].subtract(path[i - 1])).length();
  7351. }
  7352. return l;
  7353. };
  7354. return Curve3;
  7355. }());
  7356. BABYLON.Curve3 = Curve3;
  7357. // Vertex formats
  7358. var PositionNormalVertex = /** @class */ (function () {
  7359. function PositionNormalVertex(position, normal) {
  7360. if (position === void 0) { position = Vector3.Zero(); }
  7361. if (normal === void 0) { normal = Vector3.Up(); }
  7362. this.position = position;
  7363. this.normal = normal;
  7364. }
  7365. PositionNormalVertex.prototype.clone = function () {
  7366. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7367. };
  7368. return PositionNormalVertex;
  7369. }());
  7370. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7371. var PositionNormalTextureVertex = /** @class */ (function () {
  7372. function PositionNormalTextureVertex(position, normal, uv) {
  7373. if (position === void 0) { position = Vector3.Zero(); }
  7374. if (normal === void 0) { normal = Vector3.Up(); }
  7375. if (uv === void 0) { uv = Vector2.Zero(); }
  7376. this.position = position;
  7377. this.normal = normal;
  7378. this.uv = uv;
  7379. }
  7380. PositionNormalTextureVertex.prototype.clone = function () {
  7381. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7382. };
  7383. return PositionNormalTextureVertex;
  7384. }());
  7385. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7386. // Temporary pre-allocated objects for engine internal use
  7387. // usage in any internal function :
  7388. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7389. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7390. var Tmp = /** @class */ (function () {
  7391. function Tmp() {
  7392. }
  7393. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7394. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7395. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7396. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7397. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7398. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7399. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7400. Matrix.Zero(), Matrix.Zero(),
  7401. Matrix.Zero(), Matrix.Zero(),
  7402. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7403. return Tmp;
  7404. }());
  7405. BABYLON.Tmp = Tmp;
  7406. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7407. var MathTmp = /** @class */ (function () {
  7408. function MathTmp() {
  7409. }
  7410. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7411. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7412. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7413. return MathTmp;
  7414. }());
  7415. })(BABYLON || (BABYLON = {}));
  7416. //# sourceMappingURL=babylon.math.js.map
  7417. var BABYLON;
  7418. (function (BABYLON) {
  7419. var Scalar = /** @class */ (function () {
  7420. function Scalar() {
  7421. }
  7422. /**
  7423. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7424. */
  7425. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7426. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7427. var num = a - b;
  7428. return -epsilon <= num && num <= epsilon;
  7429. };
  7430. /**
  7431. * Returns a string : the upper case translation of the number i to hexadecimal.
  7432. */
  7433. Scalar.ToHex = function (i) {
  7434. var str = i.toString(16);
  7435. if (i <= 15) {
  7436. return ("0" + str).toUpperCase();
  7437. }
  7438. return str.toUpperCase();
  7439. };
  7440. /**
  7441. * Returns -1 if value is negative and +1 is value is positive.
  7442. * Returns the value itself if it's equal to zero.
  7443. */
  7444. Scalar.Sign = function (value) {
  7445. value = +value; // convert to a number
  7446. if (value === 0 || isNaN(value))
  7447. return value;
  7448. return value > 0 ? 1 : -1;
  7449. };
  7450. /**
  7451. * Returns the value itself if it's between min and max.
  7452. * Returns min if the value is lower than min.
  7453. * Returns max if the value is greater than max.
  7454. */
  7455. Scalar.Clamp = function (value, min, max) {
  7456. if (min === void 0) { min = 0; }
  7457. if (max === void 0) { max = 1; }
  7458. return Math.min(max, Math.max(min, value));
  7459. };
  7460. /**
  7461. * Returns the log2 of value.
  7462. */
  7463. Scalar.Log2 = function (value) {
  7464. return Math.log(value) * Math.LOG2E;
  7465. };
  7466. /**
  7467. * Loops the value, so that it is never larger than length and never smaller than 0.
  7468. *
  7469. * This is similar to the modulo operator but it works with floating point numbers.
  7470. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7471. * With t = 5 and length = 2.5, the result would be 0.0.
  7472. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7473. */
  7474. Scalar.Repeat = function (value, length) {
  7475. return value - Math.floor(value / length) * length;
  7476. };
  7477. /**
  7478. * Normalize the value between 0.0 and 1.0 using min and max values
  7479. */
  7480. Scalar.Normalize = function (value, min, max) {
  7481. return (value - min) / (max - min);
  7482. };
  7483. /**
  7484. * Denormalize the value from 0.0 and 1.0 using min and max values
  7485. */
  7486. Scalar.Denormalize = function (normalized, min, max) {
  7487. return (normalized * (max - min) + min);
  7488. };
  7489. /**
  7490. * Calculates the shortest difference between two given angles given in degrees.
  7491. */
  7492. Scalar.DeltaAngle = function (current, target) {
  7493. var num = Scalar.Repeat(target - current, 360.0);
  7494. if (num > 180.0) {
  7495. num -= 360.0;
  7496. }
  7497. return num;
  7498. };
  7499. /**
  7500. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7501. *
  7502. * The returned value will move back and forth between 0 and length
  7503. */
  7504. Scalar.PingPong = function (tx, length) {
  7505. var t = Scalar.Repeat(tx, length * 2.0);
  7506. return length - Math.abs(t - length);
  7507. };
  7508. /**
  7509. * Interpolates between min and max with smoothing at the limits.
  7510. *
  7511. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7512. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7513. */
  7514. Scalar.SmoothStep = function (from, to, tx) {
  7515. var t = Scalar.Clamp(tx);
  7516. t = -2.0 * t * t * t + 3.0 * t * t;
  7517. return to * t + from * (1.0 - t);
  7518. };
  7519. /**
  7520. * Moves a value current towards target.
  7521. *
  7522. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7523. * Negative values of maxDelta pushes the value away from target.
  7524. */
  7525. Scalar.MoveTowards = function (current, target, maxDelta) {
  7526. var result = 0;
  7527. if (Math.abs(target - current) <= maxDelta) {
  7528. result = target;
  7529. }
  7530. else {
  7531. result = current + Scalar.Sign(target - current) * maxDelta;
  7532. }
  7533. return result;
  7534. };
  7535. /**
  7536. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7537. *
  7538. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7539. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7540. */
  7541. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7542. var num = Scalar.DeltaAngle(current, target);
  7543. var result = 0;
  7544. if (-maxDelta < num && num < maxDelta) {
  7545. result = target;
  7546. }
  7547. else {
  7548. target = current + num;
  7549. result = Scalar.MoveTowards(current, target, maxDelta);
  7550. }
  7551. return result;
  7552. };
  7553. /**
  7554. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7555. */
  7556. Scalar.Lerp = function (start, end, amount) {
  7557. return start + ((end - start) * amount);
  7558. };
  7559. /**
  7560. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7561. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7562. */
  7563. Scalar.LerpAngle = function (start, end, amount) {
  7564. var num = Scalar.Repeat(end - start, 360.0);
  7565. if (num > 180.0) {
  7566. num -= 360.0;
  7567. }
  7568. return start + num * Scalar.Clamp(amount);
  7569. };
  7570. /**
  7571. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7572. */
  7573. Scalar.InverseLerp = function (a, b, value) {
  7574. var result = 0;
  7575. if (a != b) {
  7576. result = Scalar.Clamp((value - a) / (b - a));
  7577. }
  7578. else {
  7579. result = 0.0;
  7580. }
  7581. return result;
  7582. };
  7583. /**
  7584. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7585. */
  7586. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7587. var squared = amount * amount;
  7588. var cubed = amount * squared;
  7589. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7590. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7591. var part3 = (cubed - (2.0 * squared)) + amount;
  7592. var part4 = cubed - squared;
  7593. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7594. };
  7595. /**
  7596. * Returns a random float number between and min and max values
  7597. */
  7598. Scalar.RandomRange = function (min, max) {
  7599. if (min === max)
  7600. return min;
  7601. return ((Math.random() * (max - min)) + min);
  7602. };
  7603. /**
  7604. * This function returns percentage of a number in a given range.
  7605. *
  7606. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7607. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7608. */
  7609. Scalar.RangeToPercent = function (number, min, max) {
  7610. return ((number - min) / (max - min));
  7611. };
  7612. /**
  7613. * This function returns number that corresponds to the percentage in a given range.
  7614. *
  7615. * PercentToRange(0.34,0,100) will return 34.
  7616. */
  7617. Scalar.PercentToRange = function (percent, min, max) {
  7618. return ((max - min) * percent + min);
  7619. };
  7620. /**
  7621. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7622. * @param angle The angle to normalize in radian.
  7623. * @return The converted angle.
  7624. */
  7625. Scalar.NormalizeRadians = function (angle) {
  7626. // More precise but slower version kept for reference.
  7627. // angle = angle % Tools.TwoPi;
  7628. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7629. //if (angle > Math.PI) {
  7630. // angle -= Tools.TwoPi;
  7631. //}
  7632. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7633. return angle;
  7634. };
  7635. /**
  7636. * Two pi constants convenient for computation.
  7637. */
  7638. Scalar.TwoPi = Math.PI * 2;
  7639. return Scalar;
  7640. }());
  7641. BABYLON.Scalar = Scalar;
  7642. })(BABYLON || (BABYLON = {}));
  7643. //# sourceMappingURL=babylon.math.scalar.js.map
  7644. //# sourceMappingURL=babylon.mixins.js.map
  7645. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7646. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7647. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7648. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7649. //# sourceMappingURL=babylon.webgl2.js.map
  7650. var BABYLON;
  7651. (function (BABYLON) {
  7652. var __decoratorInitialStore = {};
  7653. var __mergedStore = {};
  7654. var _copySource = function (creationFunction, source, instanciate) {
  7655. var destination = creationFunction();
  7656. // Tags
  7657. if (BABYLON.Tags) {
  7658. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7659. }
  7660. var classStore = getMergedStore(destination);
  7661. // Properties
  7662. for (var property in classStore) {
  7663. var propertyDescriptor = classStore[property];
  7664. var sourceProperty = source[property];
  7665. var propertyType = propertyDescriptor.type;
  7666. if (sourceProperty !== undefined && sourceProperty !== null) {
  7667. switch (propertyType) {
  7668. case 0: // Value
  7669. case 6: // Mesh reference
  7670. case 11: // Camera reference
  7671. destination[property] = sourceProperty;
  7672. break;
  7673. case 1: // Texture
  7674. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7675. break;
  7676. case 2: // Color3
  7677. case 3: // FresnelParameters
  7678. case 4: // Vector2
  7679. case 5: // Vector3
  7680. case 7: // Color Curves
  7681. case 10: // Quaternion
  7682. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7683. break;
  7684. }
  7685. }
  7686. }
  7687. return destination;
  7688. };
  7689. function getDirectStore(target) {
  7690. var classKey = target.getClassName();
  7691. if (!__decoratorInitialStore[classKey]) {
  7692. __decoratorInitialStore[classKey] = {};
  7693. }
  7694. return __decoratorInitialStore[classKey];
  7695. }
  7696. /**
  7697. * Return the list of properties flagged as serializable
  7698. * @param target: host object
  7699. */
  7700. function getMergedStore(target) {
  7701. var classKey = target.getClassName();
  7702. if (__mergedStore[classKey]) {
  7703. return __mergedStore[classKey];
  7704. }
  7705. __mergedStore[classKey] = {};
  7706. var store = __mergedStore[classKey];
  7707. var currentTarget = target;
  7708. var currentKey = classKey;
  7709. while (currentKey) {
  7710. var initialStore = __decoratorInitialStore[currentKey];
  7711. for (var property in initialStore) {
  7712. store[property] = initialStore[property];
  7713. }
  7714. var parent_1 = void 0;
  7715. var done = false;
  7716. do {
  7717. parent_1 = Object.getPrototypeOf(currentTarget);
  7718. if (!parent_1.getClassName) {
  7719. done = true;
  7720. break;
  7721. }
  7722. if (parent_1.getClassName() !== currentKey) {
  7723. break;
  7724. }
  7725. currentTarget = parent_1;
  7726. } while (parent_1);
  7727. if (done) {
  7728. break;
  7729. }
  7730. currentKey = parent_1.getClassName();
  7731. currentTarget = parent_1;
  7732. }
  7733. return store;
  7734. }
  7735. function generateSerializableMember(type, sourceName) {
  7736. return function (target, propertyKey) {
  7737. var classStore = getDirectStore(target);
  7738. if (!classStore[propertyKey]) {
  7739. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7740. }
  7741. };
  7742. }
  7743. function generateExpandMember(setCallback, targetKey) {
  7744. if (targetKey === void 0) { targetKey = null; }
  7745. return function (target, propertyKey) {
  7746. var key = targetKey || ("_" + propertyKey);
  7747. Object.defineProperty(target, propertyKey, {
  7748. get: function () {
  7749. return this[key];
  7750. },
  7751. set: function (value) {
  7752. if (this[key] === value) {
  7753. return;
  7754. }
  7755. this[key] = value;
  7756. target[setCallback].apply(this);
  7757. },
  7758. enumerable: true,
  7759. configurable: true
  7760. });
  7761. };
  7762. }
  7763. function expandToProperty(callback, targetKey) {
  7764. if (targetKey === void 0) { targetKey = null; }
  7765. return generateExpandMember(callback, targetKey);
  7766. }
  7767. BABYLON.expandToProperty = expandToProperty;
  7768. function serialize(sourceName) {
  7769. return generateSerializableMember(0, sourceName); // value member
  7770. }
  7771. BABYLON.serialize = serialize;
  7772. function serializeAsTexture(sourceName) {
  7773. return generateSerializableMember(1, sourceName); // texture member
  7774. }
  7775. BABYLON.serializeAsTexture = serializeAsTexture;
  7776. function serializeAsColor3(sourceName) {
  7777. return generateSerializableMember(2, sourceName); // color3 member
  7778. }
  7779. BABYLON.serializeAsColor3 = serializeAsColor3;
  7780. function serializeAsFresnelParameters(sourceName) {
  7781. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7782. }
  7783. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7784. function serializeAsVector2(sourceName) {
  7785. return generateSerializableMember(4, sourceName); // vector2 member
  7786. }
  7787. BABYLON.serializeAsVector2 = serializeAsVector2;
  7788. function serializeAsVector3(sourceName) {
  7789. return generateSerializableMember(5, sourceName); // vector3 member
  7790. }
  7791. BABYLON.serializeAsVector3 = serializeAsVector3;
  7792. function serializeAsMeshReference(sourceName) {
  7793. return generateSerializableMember(6, sourceName); // mesh reference member
  7794. }
  7795. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7796. function serializeAsColorCurves(sourceName) {
  7797. return generateSerializableMember(7, sourceName); // color curves
  7798. }
  7799. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7800. function serializeAsColor4(sourceName) {
  7801. return generateSerializableMember(8, sourceName); // color 4
  7802. }
  7803. BABYLON.serializeAsColor4 = serializeAsColor4;
  7804. function serializeAsImageProcessingConfiguration(sourceName) {
  7805. return generateSerializableMember(9, sourceName); // image processing
  7806. }
  7807. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7808. function serializeAsQuaternion(sourceName) {
  7809. return generateSerializableMember(10, sourceName); // quaternion member
  7810. }
  7811. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7812. /**
  7813. * Decorator used to define property that can be serialized as reference to a camera
  7814. * @param sourceName defines the name of the property to decorate
  7815. */
  7816. function serializeAsCameraReference(sourceName) {
  7817. return generateSerializableMember(11, sourceName); // camera reference member
  7818. }
  7819. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7820. var SerializationHelper = /** @class */ (function () {
  7821. function SerializationHelper() {
  7822. }
  7823. SerializationHelper.Serialize = function (entity, serializationObject) {
  7824. if (!serializationObject) {
  7825. serializationObject = {};
  7826. }
  7827. // Tags
  7828. if (BABYLON.Tags) {
  7829. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7830. }
  7831. var serializedProperties = getMergedStore(entity);
  7832. // Properties
  7833. for (var property in serializedProperties) {
  7834. var propertyDescriptor = serializedProperties[property];
  7835. var targetPropertyName = propertyDescriptor.sourceName || property;
  7836. var propertyType = propertyDescriptor.type;
  7837. var sourceProperty = entity[property];
  7838. if (sourceProperty !== undefined && sourceProperty !== null) {
  7839. switch (propertyType) {
  7840. case 0: // Value
  7841. serializationObject[targetPropertyName] = sourceProperty;
  7842. break;
  7843. case 1: // Texture
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 2: // Color3
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 3: // FresnelParameters
  7850. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7851. break;
  7852. case 4: // Vector2
  7853. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7854. break;
  7855. case 5: // Vector3
  7856. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7857. break;
  7858. case 6: // Mesh reference
  7859. serializationObject[targetPropertyName] = sourceProperty.id;
  7860. break;
  7861. case 7: // Color Curves
  7862. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7863. break;
  7864. case 8: // Color 4
  7865. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7866. break;
  7867. case 9: // Image Processing
  7868. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7869. break;
  7870. case 10: // Quaternion
  7871. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7872. break;
  7873. case 11: // Camera reference
  7874. serializationObject[targetPropertyName] = sourceProperty.id;
  7875. break;
  7876. }
  7877. }
  7878. }
  7879. return serializationObject;
  7880. };
  7881. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7882. if (rootUrl === void 0) { rootUrl = null; }
  7883. var destination = creationFunction();
  7884. if (!rootUrl) {
  7885. rootUrl = "";
  7886. }
  7887. // Tags
  7888. if (BABYLON.Tags) {
  7889. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7890. }
  7891. var classStore = getMergedStore(destination);
  7892. // Properties
  7893. for (var property in classStore) {
  7894. var propertyDescriptor = classStore[property];
  7895. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7896. var propertyType = propertyDescriptor.type;
  7897. if (sourceProperty !== undefined && sourceProperty !== null) {
  7898. var dest = destination;
  7899. switch (propertyType) {
  7900. case 0: // Value
  7901. dest[property] = sourceProperty;
  7902. break;
  7903. case 1: // Texture
  7904. if (scene) {
  7905. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7906. }
  7907. break;
  7908. case 2: // Color3
  7909. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7910. break;
  7911. case 3: // FresnelParameters
  7912. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7913. break;
  7914. case 4: // Vector2
  7915. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7916. break;
  7917. case 5: // Vector3
  7918. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7919. break;
  7920. case 6: // Mesh reference
  7921. if (scene) {
  7922. dest[property] = scene.getLastMeshByID(sourceProperty);
  7923. }
  7924. break;
  7925. case 7: // Color Curves
  7926. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7927. break;
  7928. case 8: // Color 4
  7929. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7930. break;
  7931. case 9: // Image Processing
  7932. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7933. break;
  7934. case 10: // Quaternion
  7935. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7936. break;
  7937. case 11: // Camera reference
  7938. if (scene) {
  7939. dest[property] = scene.getCameraByID(sourceProperty);
  7940. }
  7941. break;
  7942. }
  7943. }
  7944. }
  7945. return destination;
  7946. };
  7947. SerializationHelper.Clone = function (creationFunction, source) {
  7948. return _copySource(creationFunction, source, false);
  7949. };
  7950. SerializationHelper.Instanciate = function (creationFunction, source) {
  7951. return _copySource(creationFunction, source, true);
  7952. };
  7953. return SerializationHelper;
  7954. }());
  7955. BABYLON.SerializationHelper = SerializationHelper;
  7956. })(BABYLON || (BABYLON = {}));
  7957. //# sourceMappingURL=babylon.decorators.js.map
  7958. var BABYLON;
  7959. (function (BABYLON) {
  7960. /**
  7961. * Wrapper class for promise with external resolve and reject.
  7962. */
  7963. var Deferred = /** @class */ (function () {
  7964. /**
  7965. * Constructor for this deferred object.
  7966. */
  7967. function Deferred() {
  7968. var _this = this;
  7969. this.promise = new Promise(function (resolve, reject) {
  7970. _this._resolve = resolve;
  7971. _this._reject = reject;
  7972. });
  7973. }
  7974. Object.defineProperty(Deferred.prototype, "resolve", {
  7975. /**
  7976. * The resolve method of the promise associated with this deferred object.
  7977. */
  7978. get: function () {
  7979. return this._resolve;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Deferred.prototype, "reject", {
  7985. /**
  7986. * The reject method of the promise associated with this deferred object.
  7987. */
  7988. get: function () {
  7989. return this._reject;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. return Deferred;
  7995. }());
  7996. BABYLON.Deferred = Deferred;
  7997. })(BABYLON || (BABYLON = {}));
  7998. //# sourceMappingURL=babylon.deferred.js.map
  7999. var BABYLON;
  8000. (function (BABYLON) {
  8001. /**
  8002. * A class serves as a medium between the observable and its observers
  8003. */
  8004. var EventState = /** @class */ (function () {
  8005. /**
  8006. * Create a new EventState
  8007. * @param mask defines the mask associated with this state
  8008. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8009. * @param target defines the original target of the state
  8010. * @param currentTarget defines the current target of the state
  8011. */
  8012. function EventState(mask, skipNextObservers, target, currentTarget) {
  8013. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8014. this.initalize(mask, skipNextObservers, target, currentTarget);
  8015. }
  8016. /**
  8017. * Initialize the current event state
  8018. * @param mask defines the mask associated with this state
  8019. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8020. * @param target defines the original target of the state
  8021. * @param currentTarget defines the current target of the state
  8022. * @returns the current event state
  8023. */
  8024. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8025. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8026. this.mask = mask;
  8027. this.skipNextObservers = skipNextObservers;
  8028. this.target = target;
  8029. this.currentTarget = currentTarget;
  8030. return this;
  8031. };
  8032. return EventState;
  8033. }());
  8034. BABYLON.EventState = EventState;
  8035. /**
  8036. * Represent an Observer registered to a given Observable object.
  8037. */
  8038. var Observer = /** @class */ (function () {
  8039. /**
  8040. * Creates a new observer
  8041. * @param callback defines the callback to call when the observer is notified
  8042. * @param mask defines the mask of the observer (used to filter notifications)
  8043. * @param scope defines the current scope used to restore the JS context
  8044. */
  8045. function Observer(
  8046. /**
  8047. * Defines the callback to call when the observer is notified
  8048. */
  8049. callback,
  8050. /**
  8051. * Defines the mask of the observer (used to filter notifications)
  8052. */
  8053. mask,
  8054. /**
  8055. * Defines the current scope used to restore the JS context
  8056. */
  8057. scope) {
  8058. if (scope === void 0) { scope = null; }
  8059. this.callback = callback;
  8060. this.mask = mask;
  8061. this.scope = scope;
  8062. /** @hidden */
  8063. this._willBeUnregistered = false;
  8064. /**
  8065. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8066. */
  8067. this.unregisterOnNextCall = false;
  8068. }
  8069. return Observer;
  8070. }());
  8071. BABYLON.Observer = Observer;
  8072. /**
  8073. * Represent a list of observers registered to multiple Observables object.
  8074. */
  8075. var MultiObserver = /** @class */ (function () {
  8076. function MultiObserver() {
  8077. }
  8078. /**
  8079. * Release associated resources
  8080. */
  8081. MultiObserver.prototype.dispose = function () {
  8082. if (this._observers && this._observables) {
  8083. for (var index = 0; index < this._observers.length; index++) {
  8084. this._observables[index].remove(this._observers[index]);
  8085. }
  8086. }
  8087. this._observers = null;
  8088. this._observables = null;
  8089. };
  8090. /**
  8091. * Raise a callback when one of the observable will notify
  8092. * @param observables defines a list of observables to watch
  8093. * @param callback defines the callback to call on notification
  8094. * @param mask defines the mask used to filter notifications
  8095. * @param scope defines the current scope used to restore the JS context
  8096. * @returns the new MultiObserver
  8097. */
  8098. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8099. if (mask === void 0) { mask = -1; }
  8100. if (scope === void 0) { scope = null; }
  8101. var result = new MultiObserver();
  8102. result._observers = new Array();
  8103. result._observables = observables;
  8104. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8105. var observable = observables_1[_i];
  8106. var observer = observable.add(callback, mask, false, scope);
  8107. if (observer) {
  8108. result._observers.push(observer);
  8109. }
  8110. }
  8111. return result;
  8112. };
  8113. return MultiObserver;
  8114. }());
  8115. BABYLON.MultiObserver = MultiObserver;
  8116. /**
  8117. * The Observable class is a simple implementation of the Observable pattern.
  8118. *
  8119. * 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.
  8120. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8121. * 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).
  8122. * 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.
  8123. */
  8124. var Observable = /** @class */ (function () {
  8125. /**
  8126. * Creates a new observable
  8127. * @param onObserverAdded defines a callback to call when a new observer is added
  8128. */
  8129. function Observable(onObserverAdded) {
  8130. this._observers = new Array();
  8131. this._eventState = new EventState(0);
  8132. if (onObserverAdded) {
  8133. this._onObserverAdded = onObserverAdded;
  8134. }
  8135. }
  8136. /**
  8137. * Create a new Observer with the specified callback
  8138. * @param callback the callback that will be executed for that Observer
  8139. * @param mask the mask used to filter observers
  8140. * @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.
  8141. * @param scope optional scope for the callback to be called from
  8142. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8143. * @returns the new observer created for the callback
  8144. */
  8145. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8146. if (mask === void 0) { mask = -1; }
  8147. if (insertFirst === void 0) { insertFirst = false; }
  8148. if (scope === void 0) { scope = null; }
  8149. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8150. if (!callback) {
  8151. return null;
  8152. }
  8153. var observer = new Observer(callback, mask, scope);
  8154. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8155. if (insertFirst) {
  8156. this._observers.unshift(observer);
  8157. }
  8158. else {
  8159. this._observers.push(observer);
  8160. }
  8161. if (this._onObserverAdded) {
  8162. this._onObserverAdded(observer);
  8163. }
  8164. return observer;
  8165. };
  8166. /**
  8167. * Remove an Observer from the Observable object
  8168. * @param observer the instance of the Observer to remove
  8169. * @returns false if it doesn't belong to this Observable
  8170. */
  8171. Observable.prototype.remove = function (observer) {
  8172. if (!observer) {
  8173. return false;
  8174. }
  8175. var index = this._observers.indexOf(observer);
  8176. if (index !== -1) {
  8177. this._observers.splice(index, 1);
  8178. return true;
  8179. }
  8180. return false;
  8181. };
  8182. /**
  8183. * Remove a callback from the Observable object
  8184. * @param callback the callback to remove
  8185. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8186. * @returns false if it doesn't belong to this Observable
  8187. */
  8188. Observable.prototype.removeCallback = function (callback, scope) {
  8189. for (var index = 0; index < this._observers.length; index++) {
  8190. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8191. this._observers.splice(index, 1);
  8192. return true;
  8193. }
  8194. }
  8195. return false;
  8196. };
  8197. Observable.prototype._deferUnregister = function (observer) {
  8198. var _this = this;
  8199. observer.unregisterOnNextCall = false;
  8200. observer._willBeUnregistered = true;
  8201. BABYLON.Tools.SetImmediate(function () {
  8202. _this.remove(observer);
  8203. });
  8204. };
  8205. /**
  8206. * Notify all Observers by calling their respective callback with the given data
  8207. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8208. * @param eventData defines the data to send to all observers
  8209. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8210. * @param target defines the original target of the state
  8211. * @param currentTarget defines the current target of the state
  8212. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8213. */
  8214. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8215. if (mask === void 0) { mask = -1; }
  8216. if (!this._observers.length) {
  8217. return true;
  8218. }
  8219. var state = this._eventState;
  8220. state.mask = mask;
  8221. state.target = target;
  8222. state.currentTarget = currentTarget;
  8223. state.skipNextObservers = false;
  8224. state.lastReturnValue = eventData;
  8225. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8226. var obs = _a[_i];
  8227. if (obs._willBeUnregistered) {
  8228. continue;
  8229. }
  8230. if (obs.mask & mask) {
  8231. if (obs.scope) {
  8232. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8233. }
  8234. else {
  8235. state.lastReturnValue = obs.callback(eventData, state);
  8236. }
  8237. if (obs.unregisterOnNextCall) {
  8238. this._deferUnregister(obs);
  8239. }
  8240. }
  8241. if (state.skipNextObservers) {
  8242. return false;
  8243. }
  8244. }
  8245. return true;
  8246. };
  8247. /**
  8248. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8249. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8250. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8251. * and it is crucial that all callbacks will be executed.
  8252. * The order of the callbacks is kept, callbacks are not executed parallel.
  8253. *
  8254. * @param eventData The data to be sent to each callback
  8255. * @param mask is used to filter observers defaults to -1
  8256. * @param target defines the callback target (see EventState)
  8257. * @param currentTarget defines he current object in the bubbling phase
  8258. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8259. */
  8260. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8261. var _this = this;
  8262. if (mask === void 0) { mask = -1; }
  8263. // create an empty promise
  8264. var p = Promise.resolve(eventData);
  8265. // no observers? return this promise.
  8266. if (!this._observers.length) {
  8267. return p;
  8268. }
  8269. var state = this._eventState;
  8270. state.mask = mask;
  8271. state.target = target;
  8272. state.currentTarget = currentTarget;
  8273. state.skipNextObservers = false;
  8274. // execute one callback after another (not using Promise.all, the order is important)
  8275. this._observers.forEach(function (obs) {
  8276. if (state.skipNextObservers) {
  8277. return;
  8278. }
  8279. if (obs._willBeUnregistered) {
  8280. return;
  8281. }
  8282. if (obs.mask & mask) {
  8283. if (obs.scope) {
  8284. p = p.then(function (lastReturnedValue) {
  8285. state.lastReturnValue = lastReturnedValue;
  8286. return obs.callback.apply(obs.scope, [eventData, state]);
  8287. });
  8288. }
  8289. else {
  8290. p = p.then(function (lastReturnedValue) {
  8291. state.lastReturnValue = lastReturnedValue;
  8292. return obs.callback(eventData, state);
  8293. });
  8294. }
  8295. if (obs.unregisterOnNextCall) {
  8296. _this._deferUnregister(obs);
  8297. }
  8298. }
  8299. });
  8300. // return the eventData
  8301. return p.then(function () { return eventData; });
  8302. };
  8303. /**
  8304. * Notify a specific observer
  8305. * @param observer defines the observer to notify
  8306. * @param eventData defines the data to be sent to each callback
  8307. * @param mask is used to filter observers defaults to -1
  8308. */
  8309. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8310. if (mask === void 0) { mask = -1; }
  8311. var state = this._eventState;
  8312. state.mask = mask;
  8313. state.skipNextObservers = false;
  8314. observer.callback(eventData, state);
  8315. };
  8316. /**
  8317. * Gets a boolean indicating if the observable has at least one observer
  8318. * @returns true is the Observable has at least one Observer registered
  8319. */
  8320. Observable.prototype.hasObservers = function () {
  8321. return this._observers.length > 0;
  8322. };
  8323. /**
  8324. * Clear the list of observers
  8325. */
  8326. Observable.prototype.clear = function () {
  8327. this._observers = new Array();
  8328. this._onObserverAdded = null;
  8329. };
  8330. /**
  8331. * Clone the current observable
  8332. * @returns a new observable
  8333. */
  8334. Observable.prototype.clone = function () {
  8335. var result = new Observable();
  8336. result._observers = this._observers.slice(0);
  8337. return result;
  8338. };
  8339. /**
  8340. * Does this observable handles observer registered with a given mask
  8341. * @param mask defines the mask to be tested
  8342. * @return whether or not one observer registered with the given mask is handeled
  8343. **/
  8344. Observable.prototype.hasSpecificMask = function (mask) {
  8345. if (mask === void 0) { mask = -1; }
  8346. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8347. var obs = _a[_i];
  8348. if (obs.mask & mask || obs.mask === mask) {
  8349. return true;
  8350. }
  8351. }
  8352. return false;
  8353. };
  8354. return Observable;
  8355. }());
  8356. BABYLON.Observable = Observable;
  8357. })(BABYLON || (BABYLON = {}));
  8358. //# sourceMappingURL=babylon.observable.js.map
  8359. var BABYLON;
  8360. (function (BABYLON) {
  8361. var SmartArray = /** @class */ (function () {
  8362. function SmartArray(capacity) {
  8363. this.length = 0;
  8364. this.data = new Array(capacity);
  8365. this._id = SmartArray._GlobalId++;
  8366. }
  8367. SmartArray.prototype.push = function (value) {
  8368. this.data[this.length++] = value;
  8369. if (this.length > this.data.length) {
  8370. this.data.length *= 2;
  8371. }
  8372. };
  8373. SmartArray.prototype.forEach = function (func) {
  8374. for (var index = 0; index < this.length; index++) {
  8375. func(this.data[index]);
  8376. }
  8377. };
  8378. SmartArray.prototype.sort = function (compareFn) {
  8379. this.data.sort(compareFn);
  8380. };
  8381. SmartArray.prototype.reset = function () {
  8382. this.length = 0;
  8383. };
  8384. SmartArray.prototype.dispose = function () {
  8385. this.reset();
  8386. if (this.data) {
  8387. this.data.length = 0;
  8388. this.data = [];
  8389. }
  8390. };
  8391. SmartArray.prototype.concat = function (array) {
  8392. if (array.length === 0) {
  8393. return;
  8394. }
  8395. if (this.length + array.length > this.data.length) {
  8396. this.data.length = (this.length + array.length) * 2;
  8397. }
  8398. for (var index = 0; index < array.length; index++) {
  8399. this.data[this.length++] = (array.data || array)[index];
  8400. }
  8401. };
  8402. SmartArray.prototype.indexOf = function (value) {
  8403. var position = this.data.indexOf(value);
  8404. if (position >= this.length) {
  8405. return -1;
  8406. }
  8407. return position;
  8408. };
  8409. SmartArray.prototype.contains = function (value) {
  8410. return this.data.indexOf(value) !== -1;
  8411. };
  8412. // Statics
  8413. SmartArray._GlobalId = 0;
  8414. return SmartArray;
  8415. }());
  8416. BABYLON.SmartArray = SmartArray;
  8417. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8418. __extends(SmartArrayNoDuplicate, _super);
  8419. function SmartArrayNoDuplicate() {
  8420. var _this = _super !== null && _super.apply(this, arguments) || this;
  8421. _this._duplicateId = 0;
  8422. return _this;
  8423. }
  8424. SmartArrayNoDuplicate.prototype.push = function (value) {
  8425. _super.prototype.push.call(this, value);
  8426. if (!value.__smartArrayFlags) {
  8427. value.__smartArrayFlags = {};
  8428. }
  8429. value.__smartArrayFlags[this._id] = this._duplicateId;
  8430. };
  8431. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8432. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8433. return false;
  8434. }
  8435. this.push(value);
  8436. return true;
  8437. };
  8438. SmartArrayNoDuplicate.prototype.reset = function () {
  8439. _super.prototype.reset.call(this);
  8440. this._duplicateId++;
  8441. };
  8442. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8443. if (array.length === 0) {
  8444. return;
  8445. }
  8446. if (this.length + array.length > this.data.length) {
  8447. this.data.length = (this.length + array.length) * 2;
  8448. }
  8449. for (var index = 0; index < array.length; index++) {
  8450. var item = (array.data || array)[index];
  8451. this.pushNoDuplicate(item);
  8452. }
  8453. };
  8454. return SmartArrayNoDuplicate;
  8455. }(SmartArray));
  8456. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8457. })(BABYLON || (BABYLON = {}));
  8458. //# sourceMappingURL=babylon.smartArray.js.map
  8459. var BABYLON;
  8460. (function (BABYLON) {
  8461. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8462. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8463. var LoadFileError = /** @class */ (function (_super) {
  8464. __extends(LoadFileError, _super);
  8465. function LoadFileError(message, request) {
  8466. var _this = _super.call(this, message) || this;
  8467. _this.request = request;
  8468. _this.name = "LoadFileError";
  8469. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8470. return _this;
  8471. }
  8472. // Polyfill for Object.setPrototypeOf if necessary.
  8473. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8474. return LoadFileError;
  8475. }(Error));
  8476. BABYLON.LoadFileError = LoadFileError;
  8477. var RetryStrategy = /** @class */ (function () {
  8478. function RetryStrategy() {
  8479. }
  8480. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8481. if (maxRetries === void 0) { maxRetries = 3; }
  8482. if (baseInterval === void 0) { baseInterval = 500; }
  8483. return function (url, request, retryIndex) {
  8484. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8485. return -1;
  8486. }
  8487. return Math.pow(2, retryIndex) * baseInterval;
  8488. };
  8489. };
  8490. return RetryStrategy;
  8491. }());
  8492. BABYLON.RetryStrategy = RetryStrategy;
  8493. // Screenshots
  8494. var screenshotCanvas;
  8495. var cloneValue = function (source, destinationObject) {
  8496. if (!source)
  8497. return null;
  8498. if (source instanceof BABYLON.Mesh) {
  8499. return null;
  8500. }
  8501. if (source instanceof BABYLON.SubMesh) {
  8502. return source.clone(destinationObject);
  8503. }
  8504. else if (source.clone) {
  8505. return source.clone();
  8506. }
  8507. return null;
  8508. };
  8509. var Tools = /** @class */ (function () {
  8510. function Tools() {
  8511. }
  8512. /**
  8513. * Interpolates between a and b via alpha
  8514. * @param a The lower value (returned when alpha = 0)
  8515. * @param b The upper value (returned when alpha = 1)
  8516. * @param alpha The interpolation-factor
  8517. * @return The mixed value
  8518. */
  8519. Tools.Mix = function (a, b, alpha) {
  8520. return a * (1 - alpha) + b * alpha;
  8521. };
  8522. Tools.Instantiate = function (className) {
  8523. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8524. return Tools.RegisteredExternalClasses[className];
  8525. }
  8526. var arr = className.split(".");
  8527. var fn = (window || this);
  8528. for (var i = 0, len = arr.length; i < len; i++) {
  8529. fn = fn[arr[i]];
  8530. }
  8531. if (typeof fn !== "function") {
  8532. return null;
  8533. }
  8534. return fn;
  8535. };
  8536. /**
  8537. * Provides a slice function that will work even on IE
  8538. * @param data defines the array to slice
  8539. * @param start defines the start of the data (optional)
  8540. * @param end defines the end of the data (optional)
  8541. * @returns the new sliced array
  8542. */
  8543. Tools.Slice = function (data, start, end) {
  8544. if (data.slice) {
  8545. return data.slice(start, end);
  8546. }
  8547. return Array.prototype.slice.call(data, start, end);
  8548. };
  8549. Tools.SetImmediate = function (action) {
  8550. if (window.setImmediate) {
  8551. window.setImmediate(action);
  8552. }
  8553. else {
  8554. setTimeout(action, 1);
  8555. }
  8556. };
  8557. Tools.IsExponentOfTwo = function (value) {
  8558. var count = 1;
  8559. do {
  8560. count *= 2;
  8561. } while (count < value);
  8562. return count === value;
  8563. };
  8564. /**
  8565. * Returns the nearest 32-bit single precision float representation of a Number
  8566. * @param value A Number. If the parameter is of a different type, it will get converted
  8567. * to a number or to NaN if it cannot be converted
  8568. * @returns number
  8569. */
  8570. Tools.FloatRound = function (value) {
  8571. if (Math.fround) {
  8572. return Math.fround(value);
  8573. }
  8574. return (Tools._tmpFloatArray[0] = value);
  8575. };
  8576. /**
  8577. * Find the next highest power of two.
  8578. * @param x Number to start search from.
  8579. * @return Next highest power of two.
  8580. */
  8581. Tools.CeilingPOT = function (x) {
  8582. x--;
  8583. x |= x >> 1;
  8584. x |= x >> 2;
  8585. x |= x >> 4;
  8586. x |= x >> 8;
  8587. x |= x >> 16;
  8588. x++;
  8589. return x;
  8590. };
  8591. /**
  8592. * Find the next lowest power of two.
  8593. * @param x Number to start search from.
  8594. * @return Next lowest power of two.
  8595. */
  8596. Tools.FloorPOT = function (x) {
  8597. x = x | (x >> 1);
  8598. x = x | (x >> 2);
  8599. x = x | (x >> 4);
  8600. x = x | (x >> 8);
  8601. x = x | (x >> 16);
  8602. return x - (x >> 1);
  8603. };
  8604. /**
  8605. * Find the nearest power of two.
  8606. * @param x Number to start search from.
  8607. * @return Next nearest power of two.
  8608. */
  8609. Tools.NearestPOT = function (x) {
  8610. var c = Tools.CeilingPOT(x);
  8611. var f = Tools.FloorPOT(x);
  8612. return (c - x) > (x - f) ? f : c;
  8613. };
  8614. Tools.GetExponentOfTwo = function (value, max, mode) {
  8615. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8616. var pot;
  8617. switch (mode) {
  8618. case BABYLON.Engine.SCALEMODE_FLOOR:
  8619. pot = Tools.FloorPOT(value);
  8620. break;
  8621. case BABYLON.Engine.SCALEMODE_NEAREST:
  8622. pot = Tools.NearestPOT(value);
  8623. break;
  8624. case BABYLON.Engine.SCALEMODE_CEILING:
  8625. default:
  8626. pot = Tools.CeilingPOT(value);
  8627. break;
  8628. }
  8629. return Math.min(pot, max);
  8630. };
  8631. Tools.GetFilename = function (path) {
  8632. var index = path.lastIndexOf("/");
  8633. if (index < 0)
  8634. return path;
  8635. return path.substring(index + 1);
  8636. };
  8637. /**
  8638. * Extracts the "folder" part of a path (everything before the filename).
  8639. * @param uri The URI to extract the info from
  8640. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8641. * @returns The "folder" part of the path
  8642. */
  8643. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8644. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8645. var index = uri.lastIndexOf("/");
  8646. if (index < 0) {
  8647. if (returnUnchangedIfNoSlash) {
  8648. return uri;
  8649. }
  8650. return "";
  8651. }
  8652. return uri.substring(0, index + 1);
  8653. };
  8654. Tools.GetDOMTextContent = function (element) {
  8655. var result = "";
  8656. var child = element.firstChild;
  8657. while (child) {
  8658. if (child.nodeType === 3) {
  8659. result += child.textContent;
  8660. }
  8661. child = child.nextSibling;
  8662. }
  8663. return result;
  8664. };
  8665. Tools.ToDegrees = function (angle) {
  8666. return angle * 180 / Math.PI;
  8667. };
  8668. Tools.ToRadians = function (angle) {
  8669. return angle * Math.PI / 180;
  8670. };
  8671. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8672. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8673. var output = "";
  8674. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8675. var i = 0;
  8676. var bytes = new Uint8Array(buffer);
  8677. while (i < bytes.length) {
  8678. chr1 = bytes[i++];
  8679. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8680. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8681. enc1 = chr1 >> 2;
  8682. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8683. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8684. enc4 = chr3 & 63;
  8685. if (isNaN(chr2)) {
  8686. enc3 = enc4 = 64;
  8687. }
  8688. else if (isNaN(chr3)) {
  8689. enc4 = 64;
  8690. }
  8691. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8692. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8693. }
  8694. return "data:image/png;base64," + output;
  8695. };
  8696. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8697. if (bias === void 0) { bias = null; }
  8698. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8699. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8700. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8701. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8702. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8703. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8704. }
  8705. if (bias) {
  8706. minimum.x -= minimum.x * bias.x + bias.y;
  8707. minimum.y -= minimum.y * bias.x + bias.y;
  8708. minimum.z -= minimum.z * bias.x + bias.y;
  8709. maximum.x += maximum.x * bias.x + bias.y;
  8710. maximum.y += maximum.y * bias.x + bias.y;
  8711. maximum.z += maximum.z * bias.x + bias.y;
  8712. }
  8713. return {
  8714. minimum: minimum,
  8715. maximum: maximum
  8716. };
  8717. };
  8718. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8719. if (bias === void 0) { bias = null; }
  8720. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8721. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8722. if (!stride) {
  8723. stride = 3;
  8724. }
  8725. for (var index = start; index < start + count; index++) {
  8726. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8727. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8728. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8729. }
  8730. if (bias) {
  8731. minimum.x -= minimum.x * bias.x + bias.y;
  8732. minimum.y -= minimum.y * bias.x + bias.y;
  8733. minimum.z -= minimum.z * bias.x + bias.y;
  8734. maximum.x += maximum.x * bias.x + bias.y;
  8735. maximum.y += maximum.y * bias.x + bias.y;
  8736. maximum.z += maximum.z * bias.x + bias.y;
  8737. }
  8738. return {
  8739. minimum: minimum,
  8740. maximum: maximum
  8741. };
  8742. };
  8743. Tools.Vector2ArrayFeeder = function (array) {
  8744. return function (index) {
  8745. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8746. var length = isFloatArray ? array.length / 2 : array.length;
  8747. if (index >= length) {
  8748. return null;
  8749. }
  8750. if (isFloatArray) {
  8751. var fa = array;
  8752. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8753. }
  8754. var a = array;
  8755. return a[index];
  8756. };
  8757. };
  8758. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8759. if (bias === void 0) { bias = null; }
  8760. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8761. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8762. var i = 0;
  8763. var cur = feeder(i++);
  8764. while (cur) {
  8765. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8766. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8767. cur = feeder(i++);
  8768. }
  8769. if (bias) {
  8770. minimum.x -= minimum.x * bias.x + bias.y;
  8771. minimum.y -= minimum.y * bias.x + bias.y;
  8772. maximum.x += maximum.x * bias.x + bias.y;
  8773. maximum.y += maximum.y * bias.x + bias.y;
  8774. }
  8775. return {
  8776. minimum: minimum,
  8777. maximum: maximum
  8778. };
  8779. };
  8780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8782. return null;
  8783. return Array.isArray(obj) ? obj : [obj];
  8784. };
  8785. // Misc.
  8786. Tools.GetPointerPrefix = function () {
  8787. var eventPrefix = "pointer";
  8788. // Check if pointer events are supported
  8789. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8790. eventPrefix = "mouse";
  8791. }
  8792. return eventPrefix;
  8793. };
  8794. /**
  8795. * @param func - the function to be called
  8796. * @param requester - the object that will request the next frame. Falls back to window.
  8797. */
  8798. Tools.QueueNewFrame = function (func, requester) {
  8799. if (!Tools.IsWindowObjectExist()) {
  8800. return setTimeout(func, 16);
  8801. }
  8802. if (!requester) {
  8803. requester = window;
  8804. }
  8805. if (requester.requestAnimationFrame) {
  8806. return requester.requestAnimationFrame(func);
  8807. }
  8808. else if (requester.msRequestAnimationFrame) {
  8809. return requester.msRequestAnimationFrame(func);
  8810. }
  8811. else if (requester.webkitRequestAnimationFrame) {
  8812. return requester.webkitRequestAnimationFrame(func);
  8813. }
  8814. else if (requester.mozRequestAnimationFrame) {
  8815. return requester.mozRequestAnimationFrame(func);
  8816. }
  8817. else if (requester.oRequestAnimationFrame) {
  8818. return requester.oRequestAnimationFrame(func);
  8819. }
  8820. else {
  8821. return window.setTimeout(func, 16);
  8822. }
  8823. };
  8824. Tools.RequestFullscreen = function (element) {
  8825. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8826. if (!requestFunction)
  8827. return;
  8828. requestFunction.call(element);
  8829. };
  8830. Tools.ExitFullscreen = function () {
  8831. if (document.exitFullscreen) {
  8832. document.exitFullscreen();
  8833. }
  8834. else if (document.mozCancelFullScreen) {
  8835. document.mozCancelFullScreen();
  8836. }
  8837. else if (document.webkitCancelFullScreen) {
  8838. document.webkitCancelFullScreen();
  8839. }
  8840. else if (document.msCancelFullScreen) {
  8841. document.msCancelFullScreen();
  8842. }
  8843. };
  8844. Tools.SetCorsBehavior = function (url, element) {
  8845. if (url && url.indexOf("data:") === 0) {
  8846. return;
  8847. }
  8848. if (Tools.CorsBehavior) {
  8849. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8850. element.crossOrigin = Tools.CorsBehavior;
  8851. }
  8852. else {
  8853. var result = Tools.CorsBehavior(url);
  8854. if (result) {
  8855. element.crossOrigin = result;
  8856. }
  8857. }
  8858. }
  8859. };
  8860. // External files
  8861. Tools.CleanUrl = function (url) {
  8862. url = url.replace(/#/mg, "%23");
  8863. return url;
  8864. };
  8865. Tools.LoadImage = function (url, onLoad, onError, database) {
  8866. if (url instanceof ArrayBuffer) {
  8867. url = Tools.EncodeArrayBufferTobase64(url);
  8868. }
  8869. url = Tools.CleanUrl(url);
  8870. url = Tools.PreprocessUrl(url);
  8871. var img = new Image();
  8872. Tools.SetCorsBehavior(url, img);
  8873. var loadHandler = function () {
  8874. img.removeEventListener("load", loadHandler);
  8875. img.removeEventListener("error", errorHandler);
  8876. onLoad(img);
  8877. };
  8878. var errorHandler = function (err) {
  8879. img.removeEventListener("load", loadHandler);
  8880. img.removeEventListener("error", errorHandler);
  8881. Tools.Error("Error while trying to load image: " + url);
  8882. if (onError) {
  8883. onError("Error while trying to load image: " + url, err);
  8884. }
  8885. };
  8886. img.addEventListener("load", loadHandler);
  8887. img.addEventListener("error", errorHandler);
  8888. var noIndexedDB = function () {
  8889. img.src = url;
  8890. };
  8891. var loadFromIndexedDB = function () {
  8892. if (database) {
  8893. database.loadImageFromDB(url, img);
  8894. }
  8895. };
  8896. //ANY database to do!
  8897. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8898. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8899. }
  8900. else {
  8901. if (url.indexOf("file:") !== -1) {
  8902. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8903. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8904. try {
  8905. var blobURL;
  8906. try {
  8907. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8908. }
  8909. catch (ex) {
  8910. // Chrome doesn't support oneTimeOnly parameter
  8911. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8912. }
  8913. img.src = blobURL;
  8914. }
  8915. catch (e) {
  8916. img.src = "";
  8917. }
  8918. return img;
  8919. }
  8920. }
  8921. noIndexedDB();
  8922. }
  8923. return img;
  8924. };
  8925. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8926. url = Tools.CleanUrl(url);
  8927. url = Tools.PreprocessUrl(url);
  8928. // If file and file input are set
  8929. if (url.indexOf("file:") !== -1) {
  8930. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8931. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8932. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8933. }
  8934. }
  8935. var loadUrl = Tools.BaseUrl + url;
  8936. var aborted = false;
  8937. var fileRequest = {
  8938. onCompleteObservable: new BABYLON.Observable(),
  8939. abort: function () { return aborted = true; },
  8940. };
  8941. var requestFile = function () {
  8942. var request = new XMLHttpRequest();
  8943. var retryHandle = null;
  8944. fileRequest.abort = function () {
  8945. aborted = true;
  8946. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8947. request.abort();
  8948. }
  8949. if (retryHandle !== null) {
  8950. clearTimeout(retryHandle);
  8951. retryHandle = null;
  8952. }
  8953. };
  8954. var retryLoop = function (retryIndex) {
  8955. request.open('GET', loadUrl, true);
  8956. if (useArrayBuffer) {
  8957. request.responseType = "arraybuffer";
  8958. }
  8959. if (onProgress) {
  8960. request.addEventListener("progress", onProgress);
  8961. }
  8962. var onLoadEnd = function () {
  8963. request.removeEventListener("loadend", onLoadEnd);
  8964. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8965. fileRequest.onCompleteObservable.clear();
  8966. };
  8967. request.addEventListener("loadend", onLoadEnd);
  8968. var onReadyStateChange = function () {
  8969. if (aborted) {
  8970. return;
  8971. }
  8972. // In case of undefined state in some browsers.
  8973. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8974. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8975. request.removeEventListener("readystatechange", onReadyStateChange);
  8976. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8977. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8978. return;
  8979. }
  8980. var retryStrategy = Tools.DefaultRetryStrategy;
  8981. if (retryStrategy) {
  8982. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8983. if (waitTime !== -1) {
  8984. // Prevent the request from completing for retry.
  8985. request.removeEventListener("loadend", onLoadEnd);
  8986. request = new XMLHttpRequest();
  8987. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8988. return;
  8989. }
  8990. }
  8991. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8992. if (onError) {
  8993. onError(request, e);
  8994. }
  8995. else {
  8996. throw e;
  8997. }
  8998. }
  8999. };
  9000. request.addEventListener("readystatechange", onReadyStateChange);
  9001. request.send();
  9002. };
  9003. retryLoop(0);
  9004. };
  9005. // Caching all files
  9006. if (database && database.enableSceneOffline) {
  9007. var noIndexedDB_1 = function () {
  9008. if (!aborted) {
  9009. requestFile();
  9010. }
  9011. };
  9012. var loadFromIndexedDB = function () {
  9013. // TODO: database needs to support aborting and should return a IFileRequest
  9014. if (aborted) {
  9015. return;
  9016. }
  9017. if (database) {
  9018. database.loadFileFromDB(url, function (data) {
  9019. if (!aborted) {
  9020. onSuccess(data);
  9021. }
  9022. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9023. }, onProgress ? function (event) {
  9024. if (!aborted) {
  9025. onProgress(event);
  9026. }
  9027. } : undefined, noIndexedDB_1, useArrayBuffer);
  9028. }
  9029. };
  9030. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9031. }
  9032. else {
  9033. requestFile();
  9034. }
  9035. return fileRequest;
  9036. };
  9037. /**
  9038. * Load a script (identified by an url). When the url returns, the
  9039. * content of this file is added into a new script element, attached to the DOM (body element)
  9040. */
  9041. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9042. var head = document.getElementsByTagName('head')[0];
  9043. var script = document.createElement('script');
  9044. script.type = 'text/javascript';
  9045. script.src = scriptUrl;
  9046. script.onload = function () {
  9047. if (onSuccess) {
  9048. onSuccess();
  9049. }
  9050. };
  9051. script.onerror = function (e) {
  9052. if (onError) {
  9053. onError("Unable to load script '" + scriptUrl + "'", e);
  9054. }
  9055. };
  9056. head.appendChild(script);
  9057. };
  9058. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9059. var reader = new FileReader();
  9060. var request = {
  9061. onCompleteObservable: new BABYLON.Observable(),
  9062. abort: function () { return reader.abort(); },
  9063. };
  9064. reader.onloadend = function (e) {
  9065. request.onCompleteObservable.notifyObservers(request);
  9066. };
  9067. reader.onload = function (e) {
  9068. //target doesn't have result from ts 1.3
  9069. callback(e.target['result']);
  9070. };
  9071. reader.onprogress = progressCallback;
  9072. reader.readAsDataURL(fileToLoad);
  9073. return request;
  9074. };
  9075. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9076. var reader = new FileReader();
  9077. var request = {
  9078. onCompleteObservable: new BABYLON.Observable(),
  9079. abort: function () { return reader.abort(); },
  9080. };
  9081. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9082. reader.onerror = function (e) {
  9083. Tools.Log("Error while reading file: " + fileToLoad.name);
  9084. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9085. };
  9086. reader.onload = function (e) {
  9087. //target doesn't have result from ts 1.3
  9088. callback(e.target['result']);
  9089. };
  9090. if (progressCallBack) {
  9091. reader.onprogress = progressCallBack;
  9092. }
  9093. if (!useArrayBuffer) {
  9094. // Asynchronous read
  9095. reader.readAsText(fileToLoad);
  9096. }
  9097. else {
  9098. reader.readAsArrayBuffer(fileToLoad);
  9099. }
  9100. return request;
  9101. };
  9102. //returns a downloadable url to a file content.
  9103. Tools.FileAsURL = function (content) {
  9104. var fileBlob = new Blob([content]);
  9105. var url = window.URL || window.webkitURL;
  9106. var link = url.createObjectURL(fileBlob);
  9107. return link;
  9108. };
  9109. // Misc.
  9110. Tools.Format = function (value, decimals) {
  9111. if (decimals === void 0) { decimals = 2; }
  9112. return value.toFixed(decimals);
  9113. };
  9114. Tools.CheckExtends = function (v, min, max) {
  9115. if (v.x < min.x)
  9116. min.x = v.x;
  9117. if (v.y < min.y)
  9118. min.y = v.y;
  9119. if (v.z < min.z)
  9120. min.z = v.z;
  9121. if (v.x > max.x)
  9122. max.x = v.x;
  9123. if (v.y > max.y)
  9124. max.y = v.y;
  9125. if (v.z > max.z)
  9126. max.z = v.z;
  9127. };
  9128. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9129. for (var prop in source) {
  9130. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9131. continue;
  9132. }
  9133. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9134. continue;
  9135. }
  9136. var sourceValue = source[prop];
  9137. var typeOfSourceValue = typeof sourceValue;
  9138. if (typeOfSourceValue === "function") {
  9139. continue;
  9140. }
  9141. try {
  9142. if (typeOfSourceValue === "object") {
  9143. if (sourceValue instanceof Array) {
  9144. destination[prop] = [];
  9145. if (sourceValue.length > 0) {
  9146. if (typeof sourceValue[0] == "object") {
  9147. for (var index = 0; index < sourceValue.length; index++) {
  9148. var clonedValue = cloneValue(sourceValue[index], destination);
  9149. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9150. destination[prop].push(clonedValue);
  9151. }
  9152. }
  9153. }
  9154. else {
  9155. destination[prop] = sourceValue.slice(0);
  9156. }
  9157. }
  9158. }
  9159. else {
  9160. destination[prop] = cloneValue(sourceValue, destination);
  9161. }
  9162. }
  9163. else {
  9164. destination[prop] = sourceValue;
  9165. }
  9166. }
  9167. catch (e) {
  9168. // Just ignore error (it could be because of a read-only property)
  9169. }
  9170. }
  9171. };
  9172. Tools.IsEmpty = function (obj) {
  9173. for (var i in obj) {
  9174. if (obj.hasOwnProperty(i)) {
  9175. return false;
  9176. }
  9177. }
  9178. return true;
  9179. };
  9180. Tools.RegisterTopRootEvents = function (events) {
  9181. for (var index = 0; index < events.length; index++) {
  9182. var event = events[index];
  9183. window.addEventListener(event.name, event.handler, false);
  9184. try {
  9185. if (window.parent) {
  9186. window.parent.addEventListener(event.name, event.handler, false);
  9187. }
  9188. }
  9189. catch (e) {
  9190. // Silently fails...
  9191. }
  9192. }
  9193. };
  9194. Tools.UnregisterTopRootEvents = function (events) {
  9195. for (var index = 0; index < events.length; index++) {
  9196. var event = events[index];
  9197. window.removeEventListener(event.name, event.handler);
  9198. try {
  9199. if (window.parent) {
  9200. window.parent.removeEventListener(event.name, event.handler);
  9201. }
  9202. }
  9203. catch (e) {
  9204. // Silently fails...
  9205. }
  9206. }
  9207. };
  9208. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9209. if (mimeType === void 0) { mimeType = "image/png"; }
  9210. // Read the contents of the framebuffer
  9211. var numberOfChannelsByLine = width * 4;
  9212. var halfHeight = height / 2;
  9213. //Reading datas from WebGL
  9214. var data = engine.readPixels(0, 0, width, height);
  9215. //To flip image on Y axis.
  9216. for (var i = 0; i < halfHeight; i++) {
  9217. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9218. var currentCell = j + i * numberOfChannelsByLine;
  9219. var targetLine = height - i - 1;
  9220. var targetCell = j + targetLine * numberOfChannelsByLine;
  9221. var temp = data[currentCell];
  9222. data[currentCell] = data[targetCell];
  9223. data[targetCell] = temp;
  9224. }
  9225. }
  9226. // Create a 2D canvas to store the result
  9227. if (!screenshotCanvas) {
  9228. screenshotCanvas = document.createElement('canvas');
  9229. }
  9230. screenshotCanvas.width = width;
  9231. screenshotCanvas.height = height;
  9232. var context = screenshotCanvas.getContext('2d');
  9233. if (context) {
  9234. // Copy the pixels to a 2D canvas
  9235. var imageData = context.createImageData(width, height);
  9236. var castData = (imageData.data);
  9237. castData.set(data);
  9238. context.putImageData(imageData, 0, 0);
  9239. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9240. }
  9241. };
  9242. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9243. if (mimeType === void 0) { mimeType = "image/png"; }
  9244. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9245. if (successCallback) {
  9246. successCallback(base64Image);
  9247. }
  9248. else {
  9249. // We need HTMLCanvasElement.toBlob for HD screenshots
  9250. if (!screenshotCanvas.toBlob) {
  9251. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9252. screenshotCanvas.toBlob = function (callback, type, quality) {
  9253. var _this = this;
  9254. setTimeout(function () {
  9255. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9256. for (var i = 0; i < len; i++) {
  9257. arr[i] = binStr.charCodeAt(i);
  9258. }
  9259. callback(new Blob([arr], { type: type || 'image/png' }));
  9260. });
  9261. };
  9262. }
  9263. screenshotCanvas.toBlob(function (blob) {
  9264. var url = URL.createObjectURL(blob);
  9265. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9266. if (("download" in document.createElement("a"))) {
  9267. var a = window.document.createElement("a");
  9268. a.href = url;
  9269. if (fileName) {
  9270. a.setAttribute("download", fileName);
  9271. }
  9272. else {
  9273. var date = new Date();
  9274. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9275. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9276. }
  9277. window.document.body.appendChild(a);
  9278. a.addEventListener("click", function () {
  9279. if (a.parentElement) {
  9280. a.parentElement.removeChild(a);
  9281. }
  9282. });
  9283. a.click();
  9284. }
  9285. else {
  9286. var newWindow = window.open("");
  9287. if (!newWindow)
  9288. return;
  9289. var img = newWindow.document.createElement("img");
  9290. img.onload = function () {
  9291. // no longer need to read the blob so it's revoked
  9292. URL.revokeObjectURL(url);
  9293. };
  9294. img.src = url;
  9295. newWindow.document.body.appendChild(img);
  9296. }
  9297. });
  9298. }
  9299. };
  9300. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9301. if (mimeType === void 0) { mimeType = "image/png"; }
  9302. var width;
  9303. var height;
  9304. // If a precision value is specified
  9305. if (size.precision) {
  9306. width = Math.round(engine.getRenderWidth() * size.precision);
  9307. height = Math.round(width / engine.getAspectRatio(camera));
  9308. }
  9309. else if (size.width && size.height) {
  9310. width = size.width;
  9311. height = size.height;
  9312. }
  9313. //If passing only width, computing height to keep display canvas ratio.
  9314. else if (size.width && !size.height) {
  9315. width = size.width;
  9316. height = Math.round(width / engine.getAspectRatio(camera));
  9317. }
  9318. //If passing only height, computing width to keep display canvas ratio.
  9319. else if (size.height && !size.width) {
  9320. height = size.height;
  9321. width = Math.round(height * engine.getAspectRatio(camera));
  9322. }
  9323. //Assuming here that "size" parameter is a number
  9324. else if (!isNaN(size)) {
  9325. height = size;
  9326. width = size;
  9327. }
  9328. else {
  9329. Tools.Error("Invalid 'size' parameter !");
  9330. return;
  9331. }
  9332. if (!screenshotCanvas) {
  9333. screenshotCanvas = document.createElement('canvas');
  9334. }
  9335. screenshotCanvas.width = width;
  9336. screenshotCanvas.height = height;
  9337. var renderContext = screenshotCanvas.getContext("2d");
  9338. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9339. var newWidth = width;
  9340. var newHeight = newWidth / ratio;
  9341. if (newHeight > height) {
  9342. newHeight = height;
  9343. newWidth = newHeight * ratio;
  9344. }
  9345. var offsetX = Math.max(0, width - newWidth) / 2;
  9346. var offsetY = Math.max(0, height - newHeight) / 2;
  9347. var renderingCanvas = engine.getRenderingCanvas();
  9348. if (renderContext && renderingCanvas) {
  9349. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9350. }
  9351. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9352. };
  9353. /**
  9354. * Generates an image screenshot from the specified camera.
  9355. *
  9356. * @param engine The engine to use for rendering
  9357. * @param camera The camera to use for rendering
  9358. * @param size This parameter can be set to a single number or to an object with the
  9359. * following (optional) properties: precision, width, height. If a single number is passed,
  9360. * it will be used for both width and height. If an object is passed, the screenshot size
  9361. * will be derived from the parameters. The precision property is a multiplier allowing
  9362. * rendering at a higher or lower resolution.
  9363. * @param successCallback The callback receives a single parameter which contains the
  9364. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9365. * src parameter of an <img> to display it.
  9366. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9367. * Check your browser for supported MIME types.
  9368. * @param samples Texture samples (default: 1)
  9369. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9370. * @param fileName A name for for the downloaded file.
  9371. * @constructor
  9372. */
  9373. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9374. if (mimeType === void 0) { mimeType = "image/png"; }
  9375. if (samples === void 0) { samples = 1; }
  9376. if (antialiasing === void 0) { antialiasing = false; }
  9377. var width;
  9378. var height;
  9379. //If a precision value is specified
  9380. if (size.precision) {
  9381. width = Math.round(engine.getRenderWidth() * size.precision);
  9382. height = Math.round(width / engine.getAspectRatio(camera));
  9383. size = { width: width, height: height };
  9384. }
  9385. else if (size.width && size.height) {
  9386. width = size.width;
  9387. height = size.height;
  9388. }
  9389. //If passing only width, computing height to keep display canvas ratio.
  9390. else if (size.width && !size.height) {
  9391. width = size.width;
  9392. height = Math.round(width / engine.getAspectRatio(camera));
  9393. size = { width: width, height: height };
  9394. }
  9395. //If passing only height, computing width to keep display canvas ratio.
  9396. else if (size.height && !size.width) {
  9397. height = size.height;
  9398. width = Math.round(height * engine.getAspectRatio(camera));
  9399. size = { width: width, height: height };
  9400. }
  9401. //Assuming here that "size" parameter is a number
  9402. else if (!isNaN(size)) {
  9403. height = size;
  9404. width = size;
  9405. }
  9406. else {
  9407. Tools.Error("Invalid 'size' parameter !");
  9408. return;
  9409. }
  9410. var scene = camera.getScene();
  9411. var previousCamera = null;
  9412. if (scene.activeCamera !== camera) {
  9413. previousCamera = scene.activeCamera;
  9414. scene.activeCamera = camera;
  9415. }
  9416. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9417. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9418. texture.renderList = null;
  9419. texture.samples = samples;
  9420. if (antialiasing) {
  9421. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9422. }
  9423. texture.onAfterRenderObservable.add(function () {
  9424. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9425. });
  9426. scene.incrementRenderId();
  9427. scene.resetCachedMaterial();
  9428. texture.render(true);
  9429. texture.dispose();
  9430. if (previousCamera) {
  9431. scene.activeCamera = previousCamera;
  9432. }
  9433. camera.getProjectionMatrix(true); // Force cache refresh;
  9434. };
  9435. // XHR response validator for local file scenario
  9436. Tools.ValidateXHRData = function (xhr, dataType) {
  9437. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9438. if (dataType === void 0) { dataType = 7; }
  9439. try {
  9440. if (dataType & 1) {
  9441. if (xhr.responseText && xhr.responseText.length > 0) {
  9442. return true;
  9443. }
  9444. else if (dataType === 1) {
  9445. return false;
  9446. }
  9447. }
  9448. if (dataType & 2) {
  9449. // Check header width and height since there is no "TGA" magic number
  9450. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9451. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9452. return true;
  9453. }
  9454. else if (dataType === 2) {
  9455. return false;
  9456. }
  9457. }
  9458. if (dataType & 4) {
  9459. // Check for the "DDS" magic number
  9460. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9461. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9462. return true;
  9463. }
  9464. else {
  9465. return false;
  9466. }
  9467. }
  9468. }
  9469. catch (e) {
  9470. // Global protection
  9471. }
  9472. return false;
  9473. };
  9474. /**
  9475. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9476. * Be aware Math.random() could cause collisions, but:
  9477. * "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"
  9478. */
  9479. Tools.RandomId = function () {
  9480. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9481. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9482. return v.toString(16);
  9483. });
  9484. };
  9485. /**
  9486. * Test if the given uri is a base64 string.
  9487. * @param uri The uri to test
  9488. * @return True if the uri is a base64 string or false otherwise.
  9489. */
  9490. Tools.IsBase64 = function (uri) {
  9491. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9492. };
  9493. /**
  9494. * Decode the given base64 uri.
  9495. * @param uri The uri to decode
  9496. * @return The decoded base64 data.
  9497. */
  9498. Tools.DecodeBase64 = function (uri) {
  9499. var decodedString = atob(uri.split(",")[1]);
  9500. var bufferLength = decodedString.length;
  9501. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9502. for (var i = 0; i < bufferLength; i++) {
  9503. bufferView[i] = decodedString.charCodeAt(i);
  9504. }
  9505. return bufferView.buffer;
  9506. };
  9507. Object.defineProperty(Tools, "NoneLogLevel", {
  9508. get: function () {
  9509. return Tools._NoneLogLevel;
  9510. },
  9511. enumerable: true,
  9512. configurable: true
  9513. });
  9514. Object.defineProperty(Tools, "MessageLogLevel", {
  9515. get: function () {
  9516. return Tools._MessageLogLevel;
  9517. },
  9518. enumerable: true,
  9519. configurable: true
  9520. });
  9521. Object.defineProperty(Tools, "WarningLogLevel", {
  9522. get: function () {
  9523. return Tools._WarningLogLevel;
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Object.defineProperty(Tools, "ErrorLogLevel", {
  9529. get: function () {
  9530. return Tools._ErrorLogLevel;
  9531. },
  9532. enumerable: true,
  9533. configurable: true
  9534. });
  9535. Object.defineProperty(Tools, "AllLogLevel", {
  9536. get: function () {
  9537. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Tools._AddLogEntry = function (entry) {
  9543. Tools._LogCache = entry + Tools._LogCache;
  9544. if (Tools.OnNewCacheEntry) {
  9545. Tools.OnNewCacheEntry(entry);
  9546. }
  9547. };
  9548. Tools._FormatMessage = function (message) {
  9549. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9550. var date = new Date();
  9551. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9552. };
  9553. Tools._LogDisabled = function (message) {
  9554. // nothing to do
  9555. };
  9556. Tools._LogEnabled = function (message) {
  9557. var formattedMessage = Tools._FormatMessage(message);
  9558. console.log("BJS - " + formattedMessage);
  9559. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9560. Tools._AddLogEntry(entry);
  9561. };
  9562. Tools._WarnDisabled = function (message) {
  9563. // nothing to do
  9564. };
  9565. Tools._WarnEnabled = function (message) {
  9566. var formattedMessage = Tools._FormatMessage(message);
  9567. console.warn("BJS - " + formattedMessage);
  9568. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9569. Tools._AddLogEntry(entry);
  9570. };
  9571. Tools._ErrorDisabled = function (message) {
  9572. // nothing to do
  9573. };
  9574. Tools._ErrorEnabled = function (message) {
  9575. Tools.errorsCount++;
  9576. var formattedMessage = Tools._FormatMessage(message);
  9577. console.error("BJS - " + formattedMessage);
  9578. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9579. Tools._AddLogEntry(entry);
  9580. };
  9581. Object.defineProperty(Tools, "LogCache", {
  9582. get: function () {
  9583. return Tools._LogCache;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Tools.ClearLogCache = function () {
  9589. Tools._LogCache = "";
  9590. Tools.errorsCount = 0;
  9591. };
  9592. Object.defineProperty(Tools, "LogLevels", {
  9593. set: function (level) {
  9594. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9595. Tools.Log = Tools._LogEnabled;
  9596. }
  9597. else {
  9598. Tools.Log = Tools._LogDisabled;
  9599. }
  9600. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9601. Tools.Warn = Tools._WarnEnabled;
  9602. }
  9603. else {
  9604. Tools.Warn = Tools._WarnDisabled;
  9605. }
  9606. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9607. Tools.Error = Tools._ErrorEnabled;
  9608. }
  9609. else {
  9610. Tools.Error = Tools._ErrorDisabled;
  9611. }
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Tools.IsWindowObjectExist = function () {
  9617. return (typeof window) !== "undefined";
  9618. };
  9619. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9620. get: function () {
  9621. return Tools._PerformanceNoneLogLevel;
  9622. },
  9623. enumerable: true,
  9624. configurable: true
  9625. });
  9626. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9627. get: function () {
  9628. return Tools._PerformanceUserMarkLogLevel;
  9629. },
  9630. enumerable: true,
  9631. configurable: true
  9632. });
  9633. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9634. get: function () {
  9635. return Tools._PerformanceConsoleLogLevel;
  9636. },
  9637. enumerable: true,
  9638. configurable: true
  9639. });
  9640. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9641. set: function (level) {
  9642. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9643. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9644. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9645. return;
  9646. }
  9647. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9648. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9649. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9650. return;
  9651. }
  9652. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9653. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9659. };
  9660. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9661. };
  9662. Tools._StartUserMark = function (counterName, condition) {
  9663. if (condition === void 0) { condition = true; }
  9664. if (!Tools._performance) {
  9665. if (!Tools.IsWindowObjectExist()) {
  9666. return;
  9667. }
  9668. Tools._performance = window.performance;
  9669. }
  9670. if (!condition || !Tools._performance.mark) {
  9671. return;
  9672. }
  9673. Tools._performance.mark(counterName + "-Begin");
  9674. };
  9675. Tools._EndUserMark = function (counterName, condition) {
  9676. if (condition === void 0) { condition = true; }
  9677. if (!condition || !Tools._performance.mark) {
  9678. return;
  9679. }
  9680. Tools._performance.mark(counterName + "-End");
  9681. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9682. };
  9683. Tools._StartPerformanceConsole = function (counterName, condition) {
  9684. if (condition === void 0) { condition = true; }
  9685. if (!condition) {
  9686. return;
  9687. }
  9688. Tools._StartUserMark(counterName, condition);
  9689. if (console.time) {
  9690. console.time(counterName);
  9691. }
  9692. };
  9693. Tools._EndPerformanceConsole = function (counterName, condition) {
  9694. if (condition === void 0) { condition = true; }
  9695. if (!condition) {
  9696. return;
  9697. }
  9698. Tools._EndUserMark(counterName, condition);
  9699. if (console.time) {
  9700. console.timeEnd(counterName);
  9701. }
  9702. };
  9703. Object.defineProperty(Tools, "Now", {
  9704. get: function () {
  9705. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9706. return window.performance.now();
  9707. }
  9708. return Date.now();
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. /**
  9714. * This method will return the name of the class used to create the instance of the given object.
  9715. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9716. * @param object the object to get the class name from
  9717. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9718. */
  9719. Tools.GetClassName = function (object, isType) {
  9720. if (isType === void 0) { isType = false; }
  9721. var name = null;
  9722. if (!isType && object.getClassName) {
  9723. name = object.getClassName();
  9724. }
  9725. else {
  9726. if (object instanceof Object) {
  9727. var classObj = isType ? object : Object.getPrototypeOf(object);
  9728. name = classObj.constructor["__bjsclassName__"];
  9729. }
  9730. if (!name) {
  9731. name = typeof object;
  9732. }
  9733. }
  9734. return name;
  9735. };
  9736. Tools.First = function (array, predicate) {
  9737. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9738. var el = array_1[_i];
  9739. if (predicate(el)) {
  9740. return el;
  9741. }
  9742. }
  9743. return null;
  9744. };
  9745. /**
  9746. * This method will return the name of the full name of the class, including its owning module (if any).
  9747. * 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).
  9748. * @param object the object to get the class name from
  9749. * @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.
  9750. */
  9751. Tools.getFullClassName = function (object, isType) {
  9752. if (isType === void 0) { isType = false; }
  9753. var className = null;
  9754. var moduleName = null;
  9755. if (!isType && object.getClassName) {
  9756. className = object.getClassName();
  9757. }
  9758. else {
  9759. if (object instanceof Object) {
  9760. var classObj = isType ? object : Object.getPrototypeOf(object);
  9761. className = classObj.constructor["__bjsclassName__"];
  9762. moduleName = classObj.constructor["__bjsmoduleName__"];
  9763. }
  9764. if (!className) {
  9765. className = typeof object;
  9766. }
  9767. }
  9768. if (!className) {
  9769. return null;
  9770. }
  9771. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9772. };
  9773. /**
  9774. * 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.
  9775. * @param array
  9776. */
  9777. Tools.arrayOrStringFeeder = function (array) {
  9778. return function (index) {
  9779. if (index >= array.length) {
  9780. return null;
  9781. }
  9782. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9783. if (val && val.getHashCode) {
  9784. val = val.getHashCode();
  9785. }
  9786. if (typeof val === "string") {
  9787. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9788. }
  9789. return val;
  9790. };
  9791. };
  9792. /**
  9793. * Compute the hashCode of a stream of number
  9794. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9795. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9796. * @return the hash code computed
  9797. */
  9798. Tools.hashCodeFromStream = function (feeder) {
  9799. // Based from here: http://stackoverflow.com/a/7616484/802124
  9800. var hash = 0;
  9801. var index = 0;
  9802. var chr = feeder(index++);
  9803. while (chr != null) {
  9804. hash = ((hash << 5) - hash) + chr;
  9805. hash |= 0; // Convert to 32bit integer
  9806. chr = feeder(index++);
  9807. }
  9808. return hash;
  9809. };
  9810. /**
  9811. * Returns a promise that resolves after the given amount of time.
  9812. * @param delay Number of milliseconds to delay
  9813. * @returns Promise that resolves after the given amount of time
  9814. */
  9815. Tools.DelayAsync = function (delay) {
  9816. return new Promise(function (resolve) {
  9817. setTimeout(function () {
  9818. resolve();
  9819. }, delay);
  9820. });
  9821. };
  9822. Tools.BaseUrl = "";
  9823. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9824. /**
  9825. * Default behaviour for cors in the application.
  9826. * It can be a string if the expected behavior is identical in the entire app.
  9827. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9828. */
  9829. Tools.CorsBehavior = "anonymous";
  9830. Tools.UseFallbackTexture = true;
  9831. /**
  9832. * Use this object to register external classes like custom textures or material
  9833. * to allow the laoders to instantiate them
  9834. */
  9835. Tools.RegisteredExternalClasses = {};
  9836. // Used in case of a texture loading problem
  9837. 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";
  9838. Tools._tmpFloatArray = new Float32Array(1);
  9839. Tools.PreprocessUrl = function (url) {
  9840. return url;
  9841. };
  9842. // Logs
  9843. Tools._NoneLogLevel = 0;
  9844. Tools._MessageLogLevel = 1;
  9845. Tools._WarningLogLevel = 2;
  9846. Tools._ErrorLogLevel = 4;
  9847. Tools._LogCache = "";
  9848. Tools.errorsCount = 0;
  9849. Tools.Log = Tools._LogEnabled;
  9850. Tools.Warn = Tools._WarnEnabled;
  9851. Tools.Error = Tools._ErrorEnabled;
  9852. // Performances
  9853. Tools._PerformanceNoneLogLevel = 0;
  9854. Tools._PerformanceUserMarkLogLevel = 1;
  9855. Tools._PerformanceConsoleLogLevel = 2;
  9856. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9857. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9858. return Tools;
  9859. }());
  9860. BABYLON.Tools = Tools;
  9861. /**
  9862. * This class is used to track a performance counter which is number based.
  9863. * The user has access to many properties which give statistics of different nature
  9864. *
  9865. * The implementer can track two kinds of Performance Counter: time and count
  9866. * 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.
  9867. * 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.
  9868. */
  9869. var PerfCounter = /** @class */ (function () {
  9870. function PerfCounter() {
  9871. this._startMonitoringTime = 0;
  9872. this._min = 0;
  9873. this._max = 0;
  9874. this._average = 0;
  9875. this._lastSecAverage = 0;
  9876. this._current = 0;
  9877. this._totalValueCount = 0;
  9878. this._totalAccumulated = 0;
  9879. this._lastSecAccumulated = 0;
  9880. this._lastSecTime = 0;
  9881. this._lastSecValueCount = 0;
  9882. }
  9883. Object.defineProperty(PerfCounter.prototype, "min", {
  9884. /**
  9885. * Returns the smallest value ever
  9886. */
  9887. get: function () {
  9888. return this._min;
  9889. },
  9890. enumerable: true,
  9891. configurable: true
  9892. });
  9893. Object.defineProperty(PerfCounter.prototype, "max", {
  9894. /**
  9895. * Returns the biggest value ever
  9896. */
  9897. get: function () {
  9898. return this._max;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(PerfCounter.prototype, "average", {
  9904. /**
  9905. * Returns the average value since the performance counter is running
  9906. */
  9907. get: function () {
  9908. return this._average;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9914. /**
  9915. * Returns the average value of the last second the counter was monitored
  9916. */
  9917. get: function () {
  9918. return this._lastSecAverage;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(PerfCounter.prototype, "current", {
  9924. /**
  9925. * Returns the current value
  9926. */
  9927. get: function () {
  9928. return this._current;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(PerfCounter.prototype, "total", {
  9934. get: function () {
  9935. return this._totalAccumulated;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(PerfCounter.prototype, "count", {
  9941. get: function () {
  9942. return this._totalValueCount;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. /**
  9948. * Call this method to start monitoring a new frame.
  9949. * 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.
  9950. */
  9951. PerfCounter.prototype.fetchNewFrame = function () {
  9952. this._totalValueCount++;
  9953. this._current = 0;
  9954. this._lastSecValueCount++;
  9955. };
  9956. /**
  9957. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9958. * @param newCount the count value to add to the monitored count
  9959. * @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.
  9960. */
  9961. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9962. if (!PerfCounter.Enabled) {
  9963. return;
  9964. }
  9965. this._current += newCount;
  9966. if (fetchResult) {
  9967. this._fetchResult();
  9968. }
  9969. };
  9970. /**
  9971. * Start monitoring this performance counter
  9972. */
  9973. PerfCounter.prototype.beginMonitoring = function () {
  9974. if (!PerfCounter.Enabled) {
  9975. return;
  9976. }
  9977. this._startMonitoringTime = Tools.Now;
  9978. };
  9979. /**
  9980. * Compute the time lapsed since the previous beginMonitoring() call.
  9981. * @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
  9982. */
  9983. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9984. if (newFrame === void 0) { newFrame = true; }
  9985. if (!PerfCounter.Enabled) {
  9986. return;
  9987. }
  9988. if (newFrame) {
  9989. this.fetchNewFrame();
  9990. }
  9991. var currentTime = Tools.Now;
  9992. this._current = currentTime - this._startMonitoringTime;
  9993. if (newFrame) {
  9994. this._fetchResult();
  9995. }
  9996. };
  9997. PerfCounter.prototype._fetchResult = function () {
  9998. this._totalAccumulated += this._current;
  9999. this._lastSecAccumulated += this._current;
  10000. // Min/Max update
  10001. this._min = Math.min(this._min, this._current);
  10002. this._max = Math.max(this._max, this._current);
  10003. this._average = this._totalAccumulated / this._totalValueCount;
  10004. // Reset last sec?
  10005. var now = Tools.Now;
  10006. if ((now - this._lastSecTime) > 1000) {
  10007. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10008. this._lastSecTime = now;
  10009. this._lastSecAccumulated = 0;
  10010. this._lastSecValueCount = 0;
  10011. }
  10012. };
  10013. PerfCounter.Enabled = true;
  10014. return PerfCounter;
  10015. }());
  10016. BABYLON.PerfCounter = PerfCounter;
  10017. /**
  10018. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10019. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10020. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10021. * @param name The name of the class, case should be preserved
  10022. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10023. */
  10024. function className(name, module) {
  10025. return function (target) {
  10026. target["__bjsclassName__"] = name;
  10027. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10028. };
  10029. }
  10030. BABYLON.className = className;
  10031. /**
  10032. * An implementation of a loop for asynchronous functions.
  10033. */
  10034. var AsyncLoop = /** @class */ (function () {
  10035. /**
  10036. * Constroctor.
  10037. * @param iterations the number of iterations.
  10038. * @param _fn the function to run each iteration
  10039. * @param _successCallback the callback that will be called upon succesful execution
  10040. * @param offset starting offset.
  10041. */
  10042. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10043. if (offset === void 0) { offset = 0; }
  10044. this.iterations = iterations;
  10045. this._fn = _fn;
  10046. this._successCallback = _successCallback;
  10047. this.index = offset - 1;
  10048. this._done = false;
  10049. }
  10050. /**
  10051. * Execute the next iteration. Must be called after the last iteration was finished.
  10052. */
  10053. AsyncLoop.prototype.executeNext = function () {
  10054. if (!this._done) {
  10055. if (this.index + 1 < this.iterations) {
  10056. ++this.index;
  10057. this._fn(this);
  10058. }
  10059. else {
  10060. this.breakLoop();
  10061. }
  10062. }
  10063. };
  10064. /**
  10065. * Break the loop and run the success callback.
  10066. */
  10067. AsyncLoop.prototype.breakLoop = function () {
  10068. this._done = true;
  10069. this._successCallback();
  10070. };
  10071. /**
  10072. * Helper function
  10073. */
  10074. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10075. if (offset === void 0) { offset = 0; }
  10076. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10077. loop.executeNext();
  10078. return loop;
  10079. };
  10080. /**
  10081. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10082. * @param iterations total number of iterations
  10083. * @param syncedIterations number of synchronous iterations in each async iteration.
  10084. * @param fn the function to call each iteration.
  10085. * @param callback a success call back that will be called when iterating stops.
  10086. * @param breakFunction a break condition (optional)
  10087. * @param timeout timeout settings for the setTimeout function. default - 0.
  10088. * @constructor
  10089. */
  10090. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10091. if (timeout === void 0) { timeout = 0; }
  10092. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10093. if (breakFunction && breakFunction())
  10094. loop.breakLoop();
  10095. else {
  10096. setTimeout(function () {
  10097. for (var i = 0; i < syncedIterations; ++i) {
  10098. var iteration = (loop.index * syncedIterations) + i;
  10099. if (iteration >= iterations)
  10100. break;
  10101. fn(iteration);
  10102. if (breakFunction && breakFunction()) {
  10103. loop.breakLoop();
  10104. break;
  10105. }
  10106. }
  10107. loop.executeNext();
  10108. }, timeout);
  10109. }
  10110. }, callback);
  10111. };
  10112. return AsyncLoop;
  10113. }());
  10114. BABYLON.AsyncLoop = AsyncLoop;
  10115. })(BABYLON || (BABYLON = {}));
  10116. //# sourceMappingURL=babylon.tools.js.map
  10117. var BABYLON;
  10118. (function (BABYLON) {
  10119. var PromiseStates;
  10120. (function (PromiseStates) {
  10121. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10122. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10123. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10124. })(PromiseStates || (PromiseStates = {}));
  10125. var FulFillmentAgregator = /** @class */ (function () {
  10126. function FulFillmentAgregator() {
  10127. this.count = 0;
  10128. this.target = 0;
  10129. this.results = [];
  10130. }
  10131. return FulFillmentAgregator;
  10132. }());
  10133. var InternalPromise = /** @class */ (function () {
  10134. function InternalPromise(resolver) {
  10135. var _this = this;
  10136. this._state = PromiseStates.Pending;
  10137. this._children = new Array();
  10138. this._rejectWasConsumed = false;
  10139. if (!resolver) {
  10140. return;
  10141. }
  10142. try {
  10143. resolver(function (value) {
  10144. _this._resolve(value);
  10145. }, function (reason) {
  10146. _this._reject(reason);
  10147. });
  10148. }
  10149. catch (e) {
  10150. this._reject(e);
  10151. }
  10152. }
  10153. Object.defineProperty(InternalPromise.prototype, "_result", {
  10154. get: function () {
  10155. return this._resultValue;
  10156. },
  10157. set: function (value) {
  10158. this._resultValue = value;
  10159. if (this._parent && this._parent._result === undefined) {
  10160. this._parent._result = value;
  10161. }
  10162. },
  10163. enumerable: true,
  10164. configurable: true
  10165. });
  10166. InternalPromise.prototype.catch = function (onRejected) {
  10167. return this.then(undefined, onRejected);
  10168. };
  10169. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10170. var _this = this;
  10171. var newPromise = new InternalPromise();
  10172. newPromise._onFulfilled = onFulfilled;
  10173. newPromise._onRejected = onRejected;
  10174. // Composition
  10175. this._children.push(newPromise);
  10176. newPromise._parent = this;
  10177. if (this._state !== PromiseStates.Pending) {
  10178. BABYLON.Tools.SetImmediate(function () {
  10179. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10180. var returnedValue = newPromise._resolve(_this._result);
  10181. if (returnedValue !== undefined && returnedValue !== null) {
  10182. if (returnedValue._state !== undefined) {
  10183. var returnedPromise = returnedValue;
  10184. newPromise._children.push(returnedPromise);
  10185. returnedPromise._parent = newPromise;
  10186. newPromise = returnedPromise;
  10187. }
  10188. else {
  10189. newPromise._result = returnedValue;
  10190. }
  10191. }
  10192. }
  10193. else {
  10194. newPromise._reject(_this._reason);
  10195. }
  10196. });
  10197. }
  10198. return newPromise;
  10199. };
  10200. InternalPromise.prototype._moveChildren = function (children) {
  10201. var _this = this;
  10202. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10203. this._children.forEach(function (child) {
  10204. child._parent = _this;
  10205. });
  10206. if (this._state === PromiseStates.Fulfilled) {
  10207. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10208. var child = _b[_i];
  10209. child._resolve(this._result);
  10210. }
  10211. }
  10212. else if (this._state === PromiseStates.Rejected) {
  10213. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10214. var child = _d[_c];
  10215. child._reject(this._reason);
  10216. }
  10217. }
  10218. var _a;
  10219. };
  10220. InternalPromise.prototype._resolve = function (value) {
  10221. try {
  10222. this._state = PromiseStates.Fulfilled;
  10223. var returnedValue = null;
  10224. if (this._onFulfilled) {
  10225. returnedValue = this._onFulfilled(value);
  10226. }
  10227. if (returnedValue !== undefined && returnedValue !== null) {
  10228. if (returnedValue._state !== undefined) {
  10229. // Transmit children
  10230. var returnedPromise = returnedValue;
  10231. returnedPromise._parent = this;
  10232. returnedPromise._moveChildren(this._children);
  10233. value = returnedPromise._result;
  10234. }
  10235. else {
  10236. value = returnedValue;
  10237. }
  10238. }
  10239. this._result = value;
  10240. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10241. var child = _a[_i];
  10242. child._resolve(value);
  10243. }
  10244. this._children.length = 0;
  10245. delete this._onFulfilled;
  10246. delete this._onRejected;
  10247. }
  10248. catch (e) {
  10249. this._reject(e, true);
  10250. }
  10251. };
  10252. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10253. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10254. this._state = PromiseStates.Rejected;
  10255. this._reason = reason;
  10256. if (this._onRejected && !onLocalThrow) {
  10257. try {
  10258. this._onRejected(reason);
  10259. this._rejectWasConsumed = true;
  10260. }
  10261. catch (e) {
  10262. reason = e;
  10263. }
  10264. }
  10265. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10266. var child = _a[_i];
  10267. if (this._rejectWasConsumed) {
  10268. child._resolve(null);
  10269. }
  10270. else {
  10271. child._reject(reason);
  10272. }
  10273. }
  10274. this._children.length = 0;
  10275. delete this._onFulfilled;
  10276. delete this._onRejected;
  10277. };
  10278. InternalPromise.resolve = function (value) {
  10279. var newPromise = new InternalPromise();
  10280. newPromise._resolve(value);
  10281. return newPromise;
  10282. };
  10283. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10284. promise.then(function (value) {
  10285. agregator.results[index] = value;
  10286. agregator.count++;
  10287. if (agregator.count === agregator.target) {
  10288. agregator.rootPromise._resolve(agregator.results);
  10289. }
  10290. return null;
  10291. }, function (reason) {
  10292. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10293. agregator.rootPromise._reject(reason);
  10294. }
  10295. });
  10296. };
  10297. InternalPromise.all = function (promises) {
  10298. var newPromise = new InternalPromise();
  10299. var agregator = new FulFillmentAgregator();
  10300. agregator.target = promises.length;
  10301. agregator.rootPromise = newPromise;
  10302. if (promises.length) {
  10303. for (var index = 0; index < promises.length; index++) {
  10304. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10305. }
  10306. }
  10307. else {
  10308. newPromise._resolve([]);
  10309. }
  10310. return newPromise;
  10311. };
  10312. InternalPromise.race = function (promises) {
  10313. var newPromise = new InternalPromise();
  10314. if (promises.length) {
  10315. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10316. var promise = promises_1[_i];
  10317. promise.then(function (value) {
  10318. if (newPromise) {
  10319. newPromise._resolve(value);
  10320. newPromise = null;
  10321. }
  10322. return null;
  10323. }, function (reason) {
  10324. if (newPromise) {
  10325. newPromise._reject(reason);
  10326. newPromise = null;
  10327. }
  10328. });
  10329. }
  10330. }
  10331. return newPromise;
  10332. };
  10333. return InternalPromise;
  10334. }());
  10335. /**
  10336. * Helper class that provides a small promise polyfill
  10337. */
  10338. var PromisePolyfill = /** @class */ (function () {
  10339. function PromisePolyfill() {
  10340. }
  10341. /**
  10342. * Static function used to check if the polyfill is required
  10343. * If this is the case then the function will inject the polyfill to window.Promise
  10344. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10345. */
  10346. PromisePolyfill.Apply = function (force) {
  10347. if (force === void 0) { force = false; }
  10348. if (force || typeof Promise === 'undefined') {
  10349. var root = window;
  10350. root.Promise = InternalPromise;
  10351. }
  10352. };
  10353. return PromisePolyfill;
  10354. }());
  10355. BABYLON.PromisePolyfill = PromisePolyfill;
  10356. })(BABYLON || (BABYLON = {}));
  10357. //# sourceMappingURL=babylon.promise.js.map
  10358. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10359. var BABYLON;
  10360. (function (BABYLON) {
  10361. /**
  10362. * Helper class to push actions to a pool of workers.
  10363. */
  10364. var WorkerPool = /** @class */ (function () {
  10365. /**
  10366. * Constructor
  10367. * @param workers Array of workers to use for actions
  10368. */
  10369. function WorkerPool(workers) {
  10370. this._pendingActions = new Array();
  10371. this._workerInfos = workers.map(function (worker) { return ({
  10372. worker: worker,
  10373. active: false
  10374. }); });
  10375. }
  10376. /**
  10377. * Terminates all workers and clears any pending actions.
  10378. */
  10379. WorkerPool.prototype.dispose = function () {
  10380. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10381. var workerInfo = _a[_i];
  10382. workerInfo.worker.terminate();
  10383. }
  10384. delete this._workerInfos;
  10385. delete this._pendingActions;
  10386. };
  10387. /**
  10388. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10389. * pended until a worker has completed its action.
  10390. * @param action The action to perform. Call onComplete when the action is complete.
  10391. */
  10392. WorkerPool.prototype.push = function (action) {
  10393. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10394. var workerInfo = _a[_i];
  10395. if (!workerInfo.active) {
  10396. this._execute(workerInfo, action);
  10397. return;
  10398. }
  10399. }
  10400. this._pendingActions.push(action);
  10401. };
  10402. WorkerPool.prototype._execute = function (workerInfo, action) {
  10403. var _this = this;
  10404. workerInfo.active = true;
  10405. action(workerInfo.worker, function () {
  10406. workerInfo.active = false;
  10407. var nextAction = _this._pendingActions.shift();
  10408. if (nextAction) {
  10409. _this._execute(workerInfo, nextAction);
  10410. }
  10411. });
  10412. };
  10413. return WorkerPool;
  10414. }());
  10415. BABYLON.WorkerPool = WorkerPool;
  10416. })(BABYLON || (BABYLON = {}));
  10417. //# sourceMappingURL=babylon.workerPool.js.map
  10418. var BABYLON;
  10419. (function (BABYLON) {
  10420. /**
  10421. * @hidden
  10422. **/
  10423. var _AlphaState = /** @class */ (function () {
  10424. /**
  10425. * Initializes the state.
  10426. */
  10427. function _AlphaState() {
  10428. this._isAlphaBlendDirty = false;
  10429. this._isBlendFunctionParametersDirty = false;
  10430. this._isBlendEquationParametersDirty = false;
  10431. this._isBlendConstantsDirty = false;
  10432. this._alphaBlend = false;
  10433. this._blendFunctionParameters = new Array(4);
  10434. this._blendEquationParameters = new Array(2);
  10435. this._blendConstants = new Array(4);
  10436. this.reset();
  10437. }
  10438. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10439. get: function () {
  10440. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10441. },
  10442. enumerable: true,
  10443. configurable: true
  10444. });
  10445. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10446. get: function () {
  10447. return this._alphaBlend;
  10448. },
  10449. set: function (value) {
  10450. if (this._alphaBlend === value) {
  10451. return;
  10452. }
  10453. this._alphaBlend = value;
  10454. this._isAlphaBlendDirty = true;
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10460. if (this._blendConstants[0] === r &&
  10461. this._blendConstants[1] === g &&
  10462. this._blendConstants[2] === b &&
  10463. this._blendConstants[3] === a) {
  10464. return;
  10465. }
  10466. this._blendConstants[0] = r;
  10467. this._blendConstants[1] = g;
  10468. this._blendConstants[2] = b;
  10469. this._blendConstants[3] = a;
  10470. this._isBlendConstantsDirty = true;
  10471. };
  10472. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10473. if (this._blendFunctionParameters[0] === value0 &&
  10474. this._blendFunctionParameters[1] === value1 &&
  10475. this._blendFunctionParameters[2] === value2 &&
  10476. this._blendFunctionParameters[3] === value3) {
  10477. return;
  10478. }
  10479. this._blendFunctionParameters[0] = value0;
  10480. this._blendFunctionParameters[1] = value1;
  10481. this._blendFunctionParameters[2] = value2;
  10482. this._blendFunctionParameters[3] = value3;
  10483. this._isBlendFunctionParametersDirty = true;
  10484. };
  10485. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10486. if (this._blendEquationParameters[0] === rgb &&
  10487. this._blendEquationParameters[1] === alpha) {
  10488. return;
  10489. }
  10490. this._blendEquationParameters[0] = rgb;
  10491. this._blendEquationParameters[1] = alpha;
  10492. this._isBlendEquationParametersDirty = true;
  10493. };
  10494. _AlphaState.prototype.reset = function () {
  10495. this._alphaBlend = false;
  10496. this._blendFunctionParameters[0] = null;
  10497. this._blendFunctionParameters[1] = null;
  10498. this._blendFunctionParameters[2] = null;
  10499. this._blendFunctionParameters[3] = null;
  10500. this._blendEquationParameters[0] = null;
  10501. this._blendEquationParameters[1] = null;
  10502. this._blendConstants[0] = null;
  10503. this._blendConstants[1] = null;
  10504. this._blendConstants[2] = null;
  10505. this._blendConstants[3] = null;
  10506. this._isAlphaBlendDirty = true;
  10507. this._isBlendFunctionParametersDirty = false;
  10508. this._isBlendEquationParametersDirty = false;
  10509. this._isBlendConstantsDirty = false;
  10510. };
  10511. _AlphaState.prototype.apply = function (gl) {
  10512. if (!this.isDirty) {
  10513. return;
  10514. }
  10515. // Alpha blend
  10516. if (this._isAlphaBlendDirty) {
  10517. if (this._alphaBlend) {
  10518. gl.enable(gl.BLEND);
  10519. }
  10520. else {
  10521. gl.disable(gl.BLEND);
  10522. }
  10523. this._isAlphaBlendDirty = false;
  10524. }
  10525. // Alpha function
  10526. if (this._isBlendFunctionParametersDirty) {
  10527. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10528. this._isBlendFunctionParametersDirty = false;
  10529. }
  10530. // Alpha equation
  10531. if (this._isBlendEquationParametersDirty) {
  10532. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10533. this._isBlendEquationParametersDirty = false;
  10534. }
  10535. // Constants
  10536. if (this._isBlendConstantsDirty) {
  10537. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10538. this._isBlendConstantsDirty = false;
  10539. }
  10540. };
  10541. return _AlphaState;
  10542. }());
  10543. BABYLON._AlphaState = _AlphaState;
  10544. })(BABYLON || (BABYLON = {}));
  10545. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10546. var BABYLON;
  10547. (function (BABYLON) {
  10548. /**
  10549. * @hidden
  10550. **/
  10551. var _DepthCullingState = /** @class */ (function () {
  10552. /**
  10553. * Initializes the state.
  10554. */
  10555. function _DepthCullingState() {
  10556. this._isDepthTestDirty = false;
  10557. this._isDepthMaskDirty = false;
  10558. this._isDepthFuncDirty = false;
  10559. this._isCullFaceDirty = false;
  10560. this._isCullDirty = false;
  10561. this._isZOffsetDirty = false;
  10562. this._isFrontFaceDirty = false;
  10563. this.reset();
  10564. }
  10565. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10566. get: function () {
  10567. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10568. },
  10569. enumerable: true,
  10570. configurable: true
  10571. });
  10572. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10573. get: function () {
  10574. return this._zOffset;
  10575. },
  10576. set: function (value) {
  10577. if (this._zOffset === value) {
  10578. return;
  10579. }
  10580. this._zOffset = value;
  10581. this._isZOffsetDirty = true;
  10582. },
  10583. enumerable: true,
  10584. configurable: true
  10585. });
  10586. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10587. get: function () {
  10588. return this._cullFace;
  10589. },
  10590. set: function (value) {
  10591. if (this._cullFace === value) {
  10592. return;
  10593. }
  10594. this._cullFace = value;
  10595. this._isCullFaceDirty = true;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10601. get: function () {
  10602. return this._cull;
  10603. },
  10604. set: function (value) {
  10605. if (this._cull === value) {
  10606. return;
  10607. }
  10608. this._cull = value;
  10609. this._isCullDirty = true;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10615. get: function () {
  10616. return this._depthFunc;
  10617. },
  10618. set: function (value) {
  10619. if (this._depthFunc === value) {
  10620. return;
  10621. }
  10622. this._depthFunc = value;
  10623. this._isDepthFuncDirty = true;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10629. get: function () {
  10630. return this._depthMask;
  10631. },
  10632. set: function (value) {
  10633. if (this._depthMask === value) {
  10634. return;
  10635. }
  10636. this._depthMask = value;
  10637. this._isDepthMaskDirty = true;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10643. get: function () {
  10644. return this._depthTest;
  10645. },
  10646. set: function (value) {
  10647. if (this._depthTest === value) {
  10648. return;
  10649. }
  10650. this._depthTest = value;
  10651. this._isDepthTestDirty = true;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10657. get: function () {
  10658. return this._frontFace;
  10659. },
  10660. set: function (value) {
  10661. if (this._frontFace === value) {
  10662. return;
  10663. }
  10664. this._frontFace = value;
  10665. this._isFrontFaceDirty = true;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. _DepthCullingState.prototype.reset = function () {
  10671. this._depthMask = true;
  10672. this._depthTest = true;
  10673. this._depthFunc = null;
  10674. this._cullFace = null;
  10675. this._cull = null;
  10676. this._zOffset = 0;
  10677. this._frontFace = null;
  10678. this._isDepthTestDirty = true;
  10679. this._isDepthMaskDirty = true;
  10680. this._isDepthFuncDirty = false;
  10681. this._isCullFaceDirty = false;
  10682. this._isCullDirty = false;
  10683. this._isZOffsetDirty = false;
  10684. this._isFrontFaceDirty = false;
  10685. };
  10686. _DepthCullingState.prototype.apply = function (gl) {
  10687. if (!this.isDirty) {
  10688. return;
  10689. }
  10690. // Cull
  10691. if (this._isCullDirty) {
  10692. if (this.cull) {
  10693. gl.enable(gl.CULL_FACE);
  10694. }
  10695. else {
  10696. gl.disable(gl.CULL_FACE);
  10697. }
  10698. this._isCullDirty = false;
  10699. }
  10700. // Cull face
  10701. if (this._isCullFaceDirty) {
  10702. gl.cullFace(this.cullFace);
  10703. this._isCullFaceDirty = false;
  10704. }
  10705. // Depth mask
  10706. if (this._isDepthMaskDirty) {
  10707. gl.depthMask(this.depthMask);
  10708. this._isDepthMaskDirty = false;
  10709. }
  10710. // Depth test
  10711. if (this._isDepthTestDirty) {
  10712. if (this.depthTest) {
  10713. gl.enable(gl.DEPTH_TEST);
  10714. }
  10715. else {
  10716. gl.disable(gl.DEPTH_TEST);
  10717. }
  10718. this._isDepthTestDirty = false;
  10719. }
  10720. // Depth func
  10721. if (this._isDepthFuncDirty) {
  10722. gl.depthFunc(this.depthFunc);
  10723. this._isDepthFuncDirty = false;
  10724. }
  10725. // zOffset
  10726. if (this._isZOffsetDirty) {
  10727. if (this.zOffset) {
  10728. gl.enable(gl.POLYGON_OFFSET_FILL);
  10729. gl.polygonOffset(this.zOffset, 0);
  10730. }
  10731. else {
  10732. gl.disable(gl.POLYGON_OFFSET_FILL);
  10733. }
  10734. this._isZOffsetDirty = false;
  10735. }
  10736. // Front face
  10737. if (this._isFrontFaceDirty) {
  10738. gl.frontFace(this.frontFace);
  10739. this._isFrontFaceDirty = false;
  10740. }
  10741. };
  10742. return _DepthCullingState;
  10743. }());
  10744. BABYLON._DepthCullingState = _DepthCullingState;
  10745. })(BABYLON || (BABYLON = {}));
  10746. //# sourceMappingURL=babylon.depthCullingState.js.map
  10747. var BABYLON;
  10748. (function (BABYLON) {
  10749. /**
  10750. * @hidden
  10751. **/
  10752. var _StencilState = /** @class */ (function () {
  10753. function _StencilState() {
  10754. this._isStencilTestDirty = false;
  10755. this._isStencilMaskDirty = false;
  10756. this._isStencilFuncDirty = false;
  10757. this._isStencilOpDirty = false;
  10758. this.reset();
  10759. }
  10760. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10761. get: function () {
  10762. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10768. get: function () {
  10769. return this._stencilFunc;
  10770. },
  10771. set: function (value) {
  10772. if (this._stencilFunc === value) {
  10773. return;
  10774. }
  10775. this._stencilFunc = value;
  10776. this._isStencilFuncDirty = true;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10782. get: function () {
  10783. return this._stencilFuncRef;
  10784. },
  10785. set: function (value) {
  10786. if (this._stencilFuncRef === value) {
  10787. return;
  10788. }
  10789. this._stencilFuncRef = value;
  10790. this._isStencilFuncDirty = true;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10796. get: function () {
  10797. return this._stencilFuncMask;
  10798. },
  10799. set: function (value) {
  10800. if (this._stencilFuncMask === value) {
  10801. return;
  10802. }
  10803. this._stencilFuncMask = value;
  10804. this._isStencilFuncDirty = true;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10810. get: function () {
  10811. return this._stencilOpStencilFail;
  10812. },
  10813. set: function (value) {
  10814. if (this._stencilOpStencilFail === value) {
  10815. return;
  10816. }
  10817. this._stencilOpStencilFail = value;
  10818. this._isStencilOpDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10824. get: function () {
  10825. return this._stencilOpDepthFail;
  10826. },
  10827. set: function (value) {
  10828. if (this._stencilOpDepthFail === value) {
  10829. return;
  10830. }
  10831. this._stencilOpDepthFail = value;
  10832. this._isStencilOpDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10838. get: function () {
  10839. return this._stencilOpStencilDepthPass;
  10840. },
  10841. set: function (value) {
  10842. if (this._stencilOpStencilDepthPass === value) {
  10843. return;
  10844. }
  10845. this._stencilOpStencilDepthPass = value;
  10846. this._isStencilOpDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10852. get: function () {
  10853. return this._stencilMask;
  10854. },
  10855. set: function (value) {
  10856. if (this._stencilMask === value) {
  10857. return;
  10858. }
  10859. this._stencilMask = value;
  10860. this._isStencilMaskDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10866. get: function () {
  10867. return this._stencilTest;
  10868. },
  10869. set: function (value) {
  10870. if (this._stencilTest === value) {
  10871. return;
  10872. }
  10873. this._stencilTest = value;
  10874. this._isStencilTestDirty = true;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. _StencilState.prototype.reset = function () {
  10880. this._stencilTest = false;
  10881. this._stencilMask = 0xFF;
  10882. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10883. this._stencilFuncRef = 1;
  10884. this._stencilFuncMask = 0xFF;
  10885. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10886. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10887. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10888. this._isStencilTestDirty = true;
  10889. this._isStencilMaskDirty = true;
  10890. this._isStencilFuncDirty = true;
  10891. this._isStencilOpDirty = true;
  10892. };
  10893. _StencilState.prototype.apply = function (gl) {
  10894. if (!this.isDirty) {
  10895. return;
  10896. }
  10897. // Stencil test
  10898. if (this._isStencilTestDirty) {
  10899. if (this.stencilTest) {
  10900. gl.enable(gl.STENCIL_TEST);
  10901. }
  10902. else {
  10903. gl.disable(gl.STENCIL_TEST);
  10904. }
  10905. this._isStencilTestDirty = false;
  10906. }
  10907. // Stencil mask
  10908. if (this._isStencilMaskDirty) {
  10909. gl.stencilMask(this.stencilMask);
  10910. this._isStencilMaskDirty = false;
  10911. }
  10912. // Stencil func
  10913. if (this._isStencilFuncDirty) {
  10914. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10915. this._isStencilFuncDirty = false;
  10916. }
  10917. // Stencil op
  10918. if (this._isStencilOpDirty) {
  10919. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10920. this._isStencilOpDirty = false;
  10921. }
  10922. };
  10923. return _StencilState;
  10924. }());
  10925. BABYLON._StencilState = _StencilState;
  10926. })(BABYLON || (BABYLON = {}));
  10927. //# sourceMappingURL=babylon.stencilState.js.map
  10928. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10929. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10930. s = arguments[i];
  10931. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10932. t[p] = s[p];
  10933. }
  10934. return t;
  10935. };
  10936. var BABYLON;
  10937. (function (BABYLON) {
  10938. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10939. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10940. };
  10941. var compileRawShader = function (gl, source, type) {
  10942. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10943. gl.shaderSource(shader, source);
  10944. gl.compileShader(shader);
  10945. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10946. var log = gl.getShaderInfoLog(shader);
  10947. if (log) {
  10948. throw new Error(log);
  10949. }
  10950. }
  10951. if (!shader) {
  10952. throw new Error("Something went wrong while compile the shader.");
  10953. }
  10954. return shader;
  10955. };
  10956. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10957. var magFilter = gl.NEAREST;
  10958. var minFilter = gl.NEAREST;
  10959. switch (samplingMode) {
  10960. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10961. magFilter = gl.LINEAR;
  10962. if (generateMipMaps) {
  10963. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10964. }
  10965. else {
  10966. minFilter = gl.LINEAR;
  10967. }
  10968. break;
  10969. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10970. magFilter = gl.LINEAR;
  10971. if (generateMipMaps) {
  10972. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10973. }
  10974. else {
  10975. minFilter = gl.LINEAR;
  10976. }
  10977. break;
  10978. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10979. magFilter = gl.NEAREST;
  10980. if (generateMipMaps) {
  10981. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10982. }
  10983. else {
  10984. minFilter = gl.NEAREST;
  10985. }
  10986. break;
  10987. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10988. magFilter = gl.NEAREST;
  10989. if (generateMipMaps) {
  10990. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10991. }
  10992. else {
  10993. minFilter = gl.NEAREST;
  10994. }
  10995. break;
  10996. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10997. magFilter = gl.NEAREST;
  10998. if (generateMipMaps) {
  10999. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11000. }
  11001. else {
  11002. minFilter = gl.LINEAR;
  11003. }
  11004. break;
  11005. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11006. magFilter = gl.NEAREST;
  11007. if (generateMipMaps) {
  11008. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11009. }
  11010. else {
  11011. minFilter = gl.LINEAR;
  11012. }
  11013. break;
  11014. case BABYLON.Texture.NEAREST_LINEAR:
  11015. magFilter = gl.NEAREST;
  11016. minFilter = gl.LINEAR;
  11017. break;
  11018. case BABYLON.Texture.NEAREST_NEAREST:
  11019. magFilter = gl.NEAREST;
  11020. minFilter = gl.NEAREST;
  11021. break;
  11022. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11023. magFilter = gl.LINEAR;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.NEAREST;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11032. magFilter = gl.LINEAR;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.NEAREST;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.LINEAR_LINEAR:
  11041. magFilter = gl.LINEAR;
  11042. minFilter = gl.LINEAR;
  11043. break;
  11044. case BABYLON.Texture.LINEAR_NEAREST:
  11045. magFilter = gl.LINEAR;
  11046. minFilter = gl.NEAREST;
  11047. break;
  11048. }
  11049. return {
  11050. min: minFilter,
  11051. mag: magFilter
  11052. };
  11053. };
  11054. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11055. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11056. var img;
  11057. var onload = function () {
  11058. loadedImages[index] = img;
  11059. loadedImages._internalCount++;
  11060. if (scene) {
  11061. scene._removePendingData(img);
  11062. }
  11063. if (loadedImages._internalCount === 6) {
  11064. onfinish(loadedImages);
  11065. }
  11066. };
  11067. var onerror = function (message, exception) {
  11068. if (scene) {
  11069. scene._removePendingData(img);
  11070. }
  11071. if (onErrorCallBack) {
  11072. onErrorCallBack(message, exception);
  11073. }
  11074. };
  11075. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11076. if (scene) {
  11077. scene._addPendingData(img);
  11078. }
  11079. };
  11080. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11081. if (onError === void 0) { onError = null; }
  11082. var loadedImages = [];
  11083. loadedImages._internalCount = 0;
  11084. for (var index = 0; index < 6; index++) {
  11085. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11086. }
  11087. };
  11088. var BufferPointer = /** @class */ (function () {
  11089. function BufferPointer() {
  11090. }
  11091. return BufferPointer;
  11092. }());
  11093. /**
  11094. * Interface for attribute information associated with buffer instanciation
  11095. */
  11096. var InstancingAttributeInfo = /** @class */ (function () {
  11097. function InstancingAttributeInfo() {
  11098. }
  11099. return InstancingAttributeInfo;
  11100. }());
  11101. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11102. /**
  11103. * Define options used to create a render target texture
  11104. */
  11105. var RenderTargetCreationOptions = /** @class */ (function () {
  11106. function RenderTargetCreationOptions() {
  11107. }
  11108. return RenderTargetCreationOptions;
  11109. }());
  11110. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11111. /**
  11112. * Define options used to create a depth texture
  11113. */
  11114. var DepthTextureCreationOptions = /** @class */ (function () {
  11115. function DepthTextureCreationOptions() {
  11116. }
  11117. return DepthTextureCreationOptions;
  11118. }());
  11119. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11120. /**
  11121. * Class used to describe the capabilities of the engine relatively to the current browser
  11122. */
  11123. var EngineCapabilities = /** @class */ (function () {
  11124. function EngineCapabilities() {
  11125. }
  11126. return EngineCapabilities;
  11127. }());
  11128. BABYLON.EngineCapabilities = EngineCapabilities;
  11129. /**
  11130. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11131. */
  11132. var Engine = /** @class */ (function () {
  11133. /**
  11134. * Creates a new engine
  11135. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11136. * @param antialias defines enable antialiasing (default: false)
  11137. * @param options defines further options to be sent to the getContext() function
  11138. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11139. */
  11140. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11141. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11142. var _this = this;
  11143. // Public members
  11144. /**
  11145. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11146. */
  11147. this.forcePOTTextures = false;
  11148. /**
  11149. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11150. */
  11151. this.isFullscreen = false;
  11152. /**
  11153. * Gets a boolean indicating if the pointer is currently locked
  11154. */
  11155. this.isPointerLock = false;
  11156. /**
  11157. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11158. */
  11159. this.cullBackFaces = true;
  11160. /**
  11161. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11162. */
  11163. this.renderEvenInBackground = true;
  11164. /**
  11165. * Gets or sets a boolean indicating that cache can be kept between frames
  11166. */
  11167. this.preventCacheWipeBetweenFrames = false;
  11168. /**
  11169. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11170. **/
  11171. this.enableOfflineSupport = false;
  11172. /**
  11173. * 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)
  11174. **/
  11175. this.disableManifestCheck = false;
  11176. /**
  11177. * Gets the list of created scenes
  11178. */
  11179. this.scenes = new Array();
  11180. /**
  11181. * Gets the list of created postprocesses
  11182. */
  11183. this.postProcesses = new Array();
  11184. // Observables
  11185. /**
  11186. * Observable event triggered each time the rendering canvas is resized
  11187. */
  11188. this.onResizeObservable = new BABYLON.Observable();
  11189. /**
  11190. * Observable event triggered each time the canvas loses focus
  11191. */
  11192. this.onCanvasBlurObservable = new BABYLON.Observable();
  11193. /**
  11194. * Observable event triggered each time the canvas gains focus
  11195. */
  11196. this.onCanvasFocusObservable = new BABYLON.Observable();
  11197. /**
  11198. * Observable event triggered each time the canvas receives pointerout event
  11199. */
  11200. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11201. /**
  11202. * Observable event triggered before each texture is initialized
  11203. */
  11204. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11205. //WebVR
  11206. this._vrDisplay = undefined;
  11207. this._vrSupported = false;
  11208. this._vrExclusivePointerMode = false;
  11209. // Uniform buffers list
  11210. /**
  11211. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11212. */
  11213. this.disableUniformBuffers = false;
  11214. /** @hidden */
  11215. this._uniformBuffers = new Array();
  11216. // Observables
  11217. /**
  11218. * Observable raised when the engine begins a new frame
  11219. */
  11220. this.onBeginFrameObservable = new BABYLON.Observable();
  11221. /**
  11222. * Observable raised when the engine ends the current frame
  11223. */
  11224. this.onEndFrameObservable = new BABYLON.Observable();
  11225. /**
  11226. * Observable raised when the engine is about to compile a shader
  11227. */
  11228. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11229. /**
  11230. * Observable raised when the engine has jsut compiled a shader
  11231. */
  11232. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11233. this._windowIsBackground = false;
  11234. this._webGLVersion = 1.0;
  11235. /** @hidden */
  11236. this._badOS = false;
  11237. /** @hidden */
  11238. this._badDesktopOS = false;
  11239. /**
  11240. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11241. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11242. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11243. */
  11244. this.disableTextureBindingOptimization = false;
  11245. /**
  11246. * Observable signaled when VR display mode changes
  11247. */
  11248. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11249. /**
  11250. * Observable signaled when VR request present is complete
  11251. */
  11252. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11253. /**
  11254. * Observable signaled when VR request present starts
  11255. */
  11256. this.onVRRequestPresentStart = new BABYLON.Observable();
  11257. this._colorWrite = true;
  11258. /** @hidden */
  11259. this._drawCalls = new BABYLON.PerfCounter();
  11260. /** @hidden */
  11261. this._textureCollisions = new BABYLON.PerfCounter();
  11262. this._renderingQueueLaunched = false;
  11263. this._activeRenderLoops = new Array();
  11264. // Deterministic lockstepMaxSteps
  11265. this._deterministicLockstep = false;
  11266. this._lockstepMaxSteps = 4;
  11267. // Lost context
  11268. /**
  11269. * Observable signaled when a context lost event is raised
  11270. */
  11271. this.onContextLostObservable = new BABYLON.Observable();
  11272. /**
  11273. * Observable signaled when a context restored event is raised
  11274. */
  11275. this.onContextRestoredObservable = new BABYLON.Observable();
  11276. this._contextWasLost = false;
  11277. this._doNotHandleContextLost = false;
  11278. // FPS
  11279. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11280. this._fps = 60;
  11281. this._deltaTime = 0;
  11282. /**
  11283. * Turn this value on if you want to pause FPS computation when in background
  11284. */
  11285. this.disablePerformanceMonitorInBackground = false;
  11286. // States
  11287. /** @hidden */
  11288. this._depthCullingState = new BABYLON._DepthCullingState();
  11289. /** @hidden */
  11290. this._stencilState = new BABYLON._StencilState();
  11291. /** @hidden */
  11292. this._alphaState = new BABYLON._AlphaState();
  11293. /** @hidden */
  11294. this._alphaMode = Engine.ALPHA_DISABLE;
  11295. // Cache
  11296. this._internalTexturesCache = new Array();
  11297. /** @hidden */
  11298. this._activeChannel = 0;
  11299. this._currentTextureChannel = -1;
  11300. /** @hidden */
  11301. this._boundTexturesCache = {};
  11302. this._compiledEffects = {};
  11303. this._vertexAttribArraysEnabled = [];
  11304. this._uintIndicesCurrentlySet = false;
  11305. this._currentBoundBuffer = new Array();
  11306. this._currentBufferPointers = new Array();
  11307. this._currentInstanceLocations = new Array();
  11308. this._currentInstanceBuffers = new Array();
  11309. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11310. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11311. this._vaoRecordInProgress = false;
  11312. this._mustWipeVertexAttributes = false;
  11313. this._nextFreeTextureSlots = new Array();
  11314. this._maxSimultaneousTextures = 0;
  11315. this._activeRequests = new Array();
  11316. // Hardware supported Compressed Textures
  11317. this._texturesSupported = new Array();
  11318. this._onVRFullScreenTriggered = function () {
  11319. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11320. //get the old size before we change
  11321. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11322. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11323. //get the width and height, change the render size
  11324. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11325. _this.setHardwareScalingLevel(1);
  11326. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11327. }
  11328. else {
  11329. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11330. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11331. }
  11332. };
  11333. this._boundUniforms = {};
  11334. // Register promises
  11335. BABYLON.PromisePolyfill.Apply();
  11336. var canvas = null;
  11337. Engine.Instances.push(this);
  11338. if (!canvasOrContext) {
  11339. return;
  11340. }
  11341. options = options || {};
  11342. if (canvasOrContext.getContext) {
  11343. canvas = canvasOrContext;
  11344. this._renderingCanvas = canvas;
  11345. if (antialias != null) {
  11346. options.antialias = antialias;
  11347. }
  11348. if (options.deterministicLockstep === undefined) {
  11349. options.deterministicLockstep = false;
  11350. }
  11351. if (options.lockstepMaxSteps === undefined) {
  11352. options.lockstepMaxSteps = 4;
  11353. }
  11354. if (options.preserveDrawingBuffer === undefined) {
  11355. options.preserveDrawingBuffer = false;
  11356. }
  11357. if (options.audioEngine === undefined) {
  11358. options.audioEngine = true;
  11359. }
  11360. if (options.stencil === undefined) {
  11361. options.stencil = true;
  11362. }
  11363. this._deterministicLockstep = options.deterministicLockstep;
  11364. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11365. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11366. // Exceptions
  11367. if (navigator && navigator.userAgent) {
  11368. var ua = navigator.userAgent;
  11369. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11370. var exception = _a[_i];
  11371. var key = exception.key;
  11372. var targets = exception.targets;
  11373. if (ua.indexOf(key) > -1) {
  11374. if (exception.capture && exception.captureConstraint) {
  11375. var capture = exception.capture;
  11376. var constraint = exception.captureConstraint;
  11377. var regex = new RegExp(capture);
  11378. var matches = regex.exec(ua);
  11379. if (matches && matches.length > 0) {
  11380. var capturedValue = parseInt(matches[matches.length - 1]);
  11381. if (capturedValue >= constraint) {
  11382. continue;
  11383. }
  11384. }
  11385. }
  11386. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11387. var target = targets_1[_b];
  11388. switch (target) {
  11389. case "uniformBuffer":
  11390. this.disableUniformBuffers = true;
  11391. break;
  11392. case "textureBindingOptimization":
  11393. this.disableTextureBindingOptimization = true;
  11394. break;
  11395. }
  11396. }
  11397. }
  11398. }
  11399. }
  11400. // GL
  11401. if (!options.disableWebGL2Support) {
  11402. try {
  11403. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11404. if (this._gl) {
  11405. this._webGLVersion = 2.0;
  11406. }
  11407. }
  11408. catch (e) {
  11409. // Do nothing
  11410. }
  11411. }
  11412. if (!this._gl) {
  11413. if (!canvas) {
  11414. throw new Error("The provided canvas is null or undefined.");
  11415. }
  11416. try {
  11417. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11418. }
  11419. catch (e) {
  11420. throw new Error("WebGL not supported");
  11421. }
  11422. }
  11423. if (!this._gl) {
  11424. throw new Error("WebGL not supported");
  11425. }
  11426. this._onCanvasFocus = function () {
  11427. _this.onCanvasFocusObservable.notifyObservers(_this);
  11428. };
  11429. this._onCanvasBlur = function () {
  11430. _this.onCanvasBlurObservable.notifyObservers(_this);
  11431. };
  11432. canvas.addEventListener("focus", this._onCanvasFocus);
  11433. canvas.addEventListener("blur", this._onCanvasBlur);
  11434. this._onBlur = function () {
  11435. if (_this.disablePerformanceMonitorInBackground) {
  11436. _this._performanceMonitor.disable();
  11437. }
  11438. _this._windowIsBackground = true;
  11439. };
  11440. this._onFocus = function () {
  11441. if (_this.disablePerformanceMonitorInBackground) {
  11442. _this._performanceMonitor.enable();
  11443. }
  11444. _this._windowIsBackground = false;
  11445. };
  11446. this._onCanvasPointerOut = function (ev) {
  11447. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11448. };
  11449. window.addEventListener("blur", this._onBlur);
  11450. window.addEventListener("focus", this._onFocus);
  11451. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11452. // Context lost
  11453. if (!this._doNotHandleContextLost) {
  11454. this._onContextLost = function (evt) {
  11455. evt.preventDefault();
  11456. _this._contextWasLost = true;
  11457. BABYLON.Tools.Warn("WebGL context lost.");
  11458. _this.onContextLostObservable.notifyObservers(_this);
  11459. };
  11460. this._onContextRestored = function (evt) {
  11461. // Adding a timeout to avoid race condition at browser level
  11462. setTimeout(function () {
  11463. // Rebuild gl context
  11464. _this._initGLContext();
  11465. // Rebuild effects
  11466. _this._rebuildEffects();
  11467. // Rebuild textures
  11468. _this._rebuildInternalTextures();
  11469. // Rebuild buffers
  11470. _this._rebuildBuffers();
  11471. // Cache
  11472. _this.wipeCaches(true);
  11473. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11474. _this.onContextRestoredObservable.notifyObservers(_this);
  11475. _this._contextWasLost = false;
  11476. }, 0);
  11477. };
  11478. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11479. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11480. }
  11481. }
  11482. else {
  11483. this._gl = canvasOrContext;
  11484. this._renderingCanvas = this._gl.canvas;
  11485. if (this._gl.renderbufferStorageMultisample) {
  11486. this._webGLVersion = 2.0;
  11487. }
  11488. options.stencil = this._gl.getContextAttributes().stencil;
  11489. }
  11490. // Viewport
  11491. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11492. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11493. this.resize();
  11494. this._isStencilEnable = options.stencil ? true : false;
  11495. this._initGLContext();
  11496. if (canvas) {
  11497. // Fullscreen
  11498. this._onFullscreenChange = function () {
  11499. if (document.fullscreen !== undefined) {
  11500. _this.isFullscreen = document.fullscreen;
  11501. }
  11502. else if (document.mozFullScreen !== undefined) {
  11503. _this.isFullscreen = document.mozFullScreen;
  11504. }
  11505. else if (document.webkitIsFullScreen !== undefined) {
  11506. _this.isFullscreen = document.webkitIsFullScreen;
  11507. }
  11508. else if (document.msIsFullScreen !== undefined) {
  11509. _this.isFullscreen = document.msIsFullScreen;
  11510. }
  11511. // Pointer lock
  11512. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11513. canvas.requestPointerLock = canvas.requestPointerLock ||
  11514. canvas.msRequestPointerLock ||
  11515. canvas.mozRequestPointerLock ||
  11516. canvas.webkitRequestPointerLock;
  11517. if (canvas.requestPointerLock) {
  11518. canvas.requestPointerLock();
  11519. }
  11520. }
  11521. };
  11522. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11523. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11524. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11525. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11526. // Pointer lock
  11527. this._onPointerLockChange = function () {
  11528. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11529. document.webkitPointerLockElement === canvas ||
  11530. document.msPointerLockElement === canvas ||
  11531. document.pointerLockElement === canvas);
  11532. };
  11533. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11534. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11535. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11536. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11537. this._onVRDisplayPointerRestricted = function () {
  11538. if (canvas) {
  11539. canvas.requestPointerLock();
  11540. }
  11541. };
  11542. this._onVRDisplayPointerUnrestricted = function () {
  11543. document.exitPointerLock();
  11544. };
  11545. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11546. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11547. }
  11548. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11549. Engine.audioEngine = new BABYLON.AudioEngine();
  11550. }
  11551. // Prepare buffer pointers
  11552. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11553. this._currentBufferPointers[i] = new BufferPointer();
  11554. }
  11555. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11556. // Load WebVR Devices
  11557. if (options.autoEnableWebVR) {
  11558. this.initWebVR();
  11559. }
  11560. // Detect if we are running on a faulty buggy OS.
  11561. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11562. // Detect if we are running on a faulty buggy desktop OS.
  11563. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11564. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11565. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11566. }
  11567. Object.defineProperty(Engine, "LastCreatedEngine", {
  11568. /**
  11569. * Gets the latest created engine
  11570. */
  11571. get: function () {
  11572. if (Engine.Instances.length === 0) {
  11573. return null;
  11574. }
  11575. return Engine.Instances[Engine.Instances.length - 1];
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. Object.defineProperty(Engine, "LastCreatedScene", {
  11581. /**
  11582. * Gets the latest created scene
  11583. */
  11584. get: function () {
  11585. var lastCreatedEngine = Engine.LastCreatedEngine;
  11586. if (!lastCreatedEngine) {
  11587. return null;
  11588. }
  11589. if (lastCreatedEngine.scenes.length === 0) {
  11590. return null;
  11591. }
  11592. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11593. },
  11594. enumerable: true,
  11595. configurable: true
  11596. });
  11597. /**
  11598. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11599. * @param flag defines which part of the materials must be marked as dirty
  11600. * @param predicate defines a predicate used to filter which materials should be affected
  11601. */
  11602. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11603. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11604. var engine = Engine.Instances[engineIndex];
  11605. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11606. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11607. }
  11608. }
  11609. };
  11610. Object.defineProperty(Engine, "NEVER", {
  11611. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11612. get: function () {
  11613. return Engine._NEVER;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "ALWAYS", {
  11619. /** 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 */
  11620. get: function () {
  11621. return Engine._ALWAYS;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "LESS", {
  11627. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11628. get: function () {
  11629. return Engine._LESS;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "EQUAL", {
  11635. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11636. get: function () {
  11637. return Engine._EQUAL;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "LEQUAL", {
  11643. /** 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 */
  11644. get: function () {
  11645. return Engine._LEQUAL;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "GREATER", {
  11651. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11652. get: function () {
  11653. return Engine._GREATER;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "GEQUAL", {
  11659. /** 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 */
  11660. get: function () {
  11661. return Engine._GEQUAL;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "NOTEQUAL", {
  11667. /** 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 */
  11668. get: function () {
  11669. return Engine._NOTEQUAL;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Engine, "KEEP", {
  11675. /** Passed to stencilOperation to specify that stencil value must be kept */
  11676. get: function () {
  11677. return Engine._KEEP;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(Engine, "REPLACE", {
  11683. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11684. get: function () {
  11685. return Engine._REPLACE;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "INCR", {
  11691. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11692. get: function () {
  11693. return Engine._INCR;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "DECR", {
  11699. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11700. get: function () {
  11701. return Engine._DECR;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "INVERT", {
  11707. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11708. get: function () {
  11709. return Engine._INVERT;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "INCR_WRAP", {
  11715. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11716. get: function () {
  11717. return Engine._INCR_WRAP;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "DECR_WRAP", {
  11723. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11724. get: function () {
  11725. return Engine._DECR_WRAP;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11731. // Alpha
  11732. /** Defines that alpha blending is disabled */
  11733. get: function () {
  11734. return Engine._ALPHA_DISABLE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11740. /** Defines that alpha blending to SRC + DEST */
  11741. get: function () {
  11742. return Engine._ALPHA_ONEONE;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "ALPHA_ADD", {
  11748. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11749. get: function () {
  11750. return Engine._ALPHA_ADD;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11756. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11757. get: function () {
  11758. return Engine._ALPHA_COMBINE;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11764. /** Defines that alpha blending to DEST - SRC * DEST */
  11765. get: function () {
  11766. return Engine._ALPHA_SUBTRACT;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11772. /** Defines that alpha blending to SRC * DEST */
  11773. get: function () {
  11774. return Engine._ALPHA_MULTIPLY;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11780. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11781. get: function () {
  11782. return Engine._ALPHA_MAXIMIZED;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11788. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11789. get: function () {
  11790. return Engine._ALPHA_PREMULTIPLIED;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11796. /**
  11797. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11798. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11799. */
  11800. get: function () {
  11801. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11807. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11808. get: function () {
  11809. return Engine._ALPHA_INTERPOLATE;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11815. /**
  11816. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11817. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11818. */
  11819. get: function () {
  11820. return Engine._ALPHA_SCREENMODE;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11826. // Delays
  11827. /** Defines that the ressource is not delayed*/
  11828. get: function () {
  11829. return Engine._DELAYLOADSTATE_NONE;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11835. /** Defines that the ressource was successfully delay loaded */
  11836. get: function () {
  11837. return Engine._DELAYLOADSTATE_LOADED;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11843. /** Defines that the ressource is currently delay loading */
  11844. get: function () {
  11845. return Engine._DELAYLOADSTATE_LOADING;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11851. /** Defines that the ressource is delayed and has not started loading */
  11852. get: function () {
  11853. return Engine._DELAYLOADSTATE_NOTLOADED;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11859. /** ALPHA */
  11860. get: function () {
  11861. return Engine._TEXTUREFORMAT_ALPHA;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11867. /** LUMINANCE */
  11868. get: function () {
  11869. return Engine._TEXTUREFORMAT_LUMINANCE;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11875. /**
  11876. * R32F
  11877. */
  11878. get: function () {
  11879. return Engine._TEXTUREFORMAT_R32F;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11885. /**
  11886. * RG32F
  11887. */
  11888. get: function () {
  11889. return Engine._TEXTUREFORMAT_RG32F;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11895. /**
  11896. * RGB32F
  11897. */
  11898. get: function () {
  11899. return Engine._TEXTUREFORMAT_RGB32F;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11905. /**
  11906. * RGBA32F
  11907. */
  11908. get: function () {
  11909. return Engine._TEXTUREFORMAT_RGBA32F;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11915. /** LUMINANCE_ALPHA */
  11916. get: function () {
  11917. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11923. /** RGB */
  11924. get: function () {
  11925. return Engine._TEXTUREFORMAT_RGB;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11931. /** RGBA */
  11932. get: function () {
  11933. return Engine._TEXTUREFORMAT_RGBA;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11939. /** UNSIGNED_INT */
  11940. get: function () {
  11941. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11947. /** FLOAT */
  11948. get: function () {
  11949. return Engine._TEXTURETYPE_FLOAT;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11955. /** HALF_FLOAT */
  11956. get: function () {
  11957. return Engine._TEXTURETYPE_HALF_FLOAT;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11963. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11964. get: function () {
  11965. return Engine._SCALEMODE_FLOOR;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11971. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11972. get: function () {
  11973. return Engine._SCALEMODE_NEAREST;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11979. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11980. get: function () {
  11981. return Engine._SCALEMODE_CEILING;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Engine, "Version", {
  11987. /**
  11988. * Returns the current version of the framework
  11989. */
  11990. get: function () {
  11991. return "3.2.0-rc.4";
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11997. /**
  11998. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11999. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12000. */
  12001. get: function () {
  12002. return this._vrExclusivePointerMode;
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12008. /**
  12009. * Gets a boolean indicating that the engine supports uniform buffers
  12010. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12011. */
  12012. get: function () {
  12013. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12019. /**
  12020. * Gets a boolean indicating that only power of 2 textures are supported
  12021. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12022. */
  12023. get: function () {
  12024. return this._webGLVersion < 2 || this.forcePOTTextures;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12030. /**
  12031. * Gets the performance monitor attached to this engine
  12032. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12033. */
  12034. get: function () {
  12035. return this._performanceMonitor;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12041. /**
  12042. * Gets the list of texture formats supported
  12043. */
  12044. get: function () {
  12045. return this._texturesSupported;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12051. /**
  12052. * Gets the list of texture formats in use
  12053. */
  12054. get: function () {
  12055. return this._textureFormatInUse;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "currentViewport", {
  12061. /**
  12062. * Gets the current viewport
  12063. */
  12064. get: function () {
  12065. return this._cachedViewport;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12071. /**
  12072. * Gets the default empty texture
  12073. */
  12074. get: function () {
  12075. if (!this._emptyTexture) {
  12076. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12077. }
  12078. return this._emptyTexture;
  12079. },
  12080. enumerable: true,
  12081. configurable: true
  12082. });
  12083. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12084. /**
  12085. * Gets the default empty 3D texture
  12086. */
  12087. get: function () {
  12088. if (!this._emptyTexture3D) {
  12089. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12090. }
  12091. return this._emptyTexture3D;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12097. /**
  12098. * Gets the default empty cube texture
  12099. */
  12100. get: function () {
  12101. if (!this._emptyCubeTexture) {
  12102. var faceData = new Uint8Array(4);
  12103. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12104. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12105. }
  12106. return this._emptyCubeTexture;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Engine.prototype._rebuildInternalTextures = function () {
  12112. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12113. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12114. var internalTexture = currentState_1[_i];
  12115. internalTexture._rebuild();
  12116. }
  12117. };
  12118. Engine.prototype._rebuildEffects = function () {
  12119. for (var key in this._compiledEffects) {
  12120. var effect = this._compiledEffects[key];
  12121. effect._prepareEffect();
  12122. }
  12123. BABYLON.Effect.ResetCache();
  12124. };
  12125. Engine.prototype._rebuildBuffers = function () {
  12126. // Index / Vertex
  12127. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12128. var scene = _a[_i];
  12129. scene.resetCachedMaterial();
  12130. scene._rebuildGeometries();
  12131. scene._rebuildTextures();
  12132. }
  12133. // Uniforms
  12134. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12135. var uniformBuffer = _c[_b];
  12136. uniformBuffer._rebuild();
  12137. }
  12138. };
  12139. Engine.prototype._initGLContext = function () {
  12140. // Caps
  12141. this._caps = new EngineCapabilities();
  12142. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12143. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12144. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12145. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12146. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12147. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12148. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12149. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12150. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12151. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12152. // Infos
  12153. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12154. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12155. if (rendererInfo != null) {
  12156. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12157. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12158. }
  12159. if (!this._glVendor) {
  12160. this._glVendor = "Unknown vendor";
  12161. }
  12162. if (!this._glRenderer) {
  12163. this._glRenderer = "Unknown renderer";
  12164. }
  12165. // Constants
  12166. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12167. if (this._gl.RGBA16F !== 0x881A) {
  12168. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12169. }
  12170. if (this._gl.RGBA32F !== 0x8814) {
  12171. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12172. }
  12173. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12174. this._gl.DEPTH24_STENCIL8 = 35056;
  12175. }
  12176. // Extensions
  12177. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12178. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12179. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12180. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12181. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12182. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12183. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12184. 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');
  12185. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12186. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12187. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12188. this._caps.highPrecisionShaderSupported = true;
  12189. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12190. if (this._caps.timerQuery) {
  12191. if (this._webGLVersion === 1) {
  12192. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12193. }
  12194. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12195. }
  12196. // Checks if some of the format renders first to allow the use of webgl inspector.
  12197. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12198. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12199. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12200. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12201. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12202. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12203. if (this._webGLVersion > 1) {
  12204. this._gl.HALF_FLOAT_OES = 0x140B;
  12205. }
  12206. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12207. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12208. // Draw buffers
  12209. if (this._webGLVersion > 1) {
  12210. this._caps.drawBuffersExtension = true;
  12211. }
  12212. else {
  12213. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12214. if (drawBuffersExtension !== null) {
  12215. this._caps.drawBuffersExtension = true;
  12216. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12217. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12218. for (var i = 0; i < 16; i++) {
  12219. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12220. }
  12221. }
  12222. else {
  12223. this._caps.drawBuffersExtension = false;
  12224. }
  12225. }
  12226. // Depth Texture
  12227. if (this._webGLVersion > 1) {
  12228. this._caps.depthTextureExtension = true;
  12229. }
  12230. else {
  12231. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12232. if (depthTextureExtension != null) {
  12233. this._caps.depthTextureExtension = true;
  12234. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12235. }
  12236. }
  12237. // Vertex array object
  12238. if (this._webGLVersion > 1) {
  12239. this._caps.vertexArrayObject = true;
  12240. }
  12241. else {
  12242. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12243. if (vertexArrayObjectExtension != null) {
  12244. this._caps.vertexArrayObject = true;
  12245. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12246. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12247. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12248. }
  12249. else {
  12250. this._caps.vertexArrayObject = false;
  12251. }
  12252. }
  12253. // Instances count
  12254. if (this._webGLVersion > 1) {
  12255. this._caps.instancedArrays = true;
  12256. }
  12257. else {
  12258. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12259. if (instanceExtension != null) {
  12260. this._caps.instancedArrays = true;
  12261. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12262. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12263. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12264. }
  12265. else {
  12266. this._caps.instancedArrays = false;
  12267. }
  12268. }
  12269. // Intelligently add supported compressed formats in order to check for.
  12270. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12271. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12272. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12273. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12274. if (this._caps.astc)
  12275. this.texturesSupported.push('-astc.ktx');
  12276. if (this._caps.s3tc)
  12277. this.texturesSupported.push('-dxt.ktx');
  12278. if (this._caps.pvrtc)
  12279. this.texturesSupported.push('-pvrtc.ktx');
  12280. if (this._caps.etc2)
  12281. this.texturesSupported.push('-etc2.ktx');
  12282. if (this._caps.etc1)
  12283. this.texturesSupported.push('-etc1.ktx');
  12284. if (this._gl.getShaderPrecisionFormat) {
  12285. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12286. if (highp) {
  12287. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12288. }
  12289. }
  12290. // Depth buffer
  12291. this.setDepthBuffer(true);
  12292. this.setDepthFunctionToLessOrEqual();
  12293. this.setDepthWrite(true);
  12294. // Texture maps
  12295. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12296. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12297. this._nextFreeTextureSlots.push(slot);
  12298. }
  12299. };
  12300. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12301. /**
  12302. * Gets version of the current webGL context
  12303. */
  12304. get: function () {
  12305. return this._webGLVersion;
  12306. },
  12307. enumerable: true,
  12308. configurable: true
  12309. });
  12310. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12311. /**
  12312. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12313. */
  12314. get: function () {
  12315. return this._isStencilEnable;
  12316. },
  12317. enumerable: true,
  12318. configurable: true
  12319. });
  12320. Engine.prototype._prepareWorkingCanvas = function () {
  12321. if (this._workingCanvas) {
  12322. return;
  12323. }
  12324. this._workingCanvas = document.createElement("canvas");
  12325. var context = this._workingCanvas.getContext("2d");
  12326. if (context) {
  12327. this._workingContext = context;
  12328. }
  12329. };
  12330. /**
  12331. * Reset the texture cache to empty state
  12332. */
  12333. Engine.prototype.resetTextureCache = function () {
  12334. for (var key in this._boundTexturesCache) {
  12335. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12336. continue;
  12337. }
  12338. var boundTexture = this._boundTexturesCache[key];
  12339. if (boundTexture) {
  12340. this._removeDesignatedSlot(boundTexture);
  12341. }
  12342. this._boundTexturesCache[key] = null;
  12343. }
  12344. if (!this.disableTextureBindingOptimization) {
  12345. this._nextFreeTextureSlots = [];
  12346. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12347. this._nextFreeTextureSlots.push(slot);
  12348. }
  12349. }
  12350. this._currentTextureChannel = -1;
  12351. };
  12352. /**
  12353. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12354. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12355. * @returns true if engine is in deterministic lock step mode
  12356. */
  12357. Engine.prototype.isDeterministicLockStep = function () {
  12358. return this._deterministicLockstep;
  12359. };
  12360. /**
  12361. * Gets the max steps when engine is running in deterministic lock step
  12362. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12363. * @returns the max steps
  12364. */
  12365. Engine.prototype.getLockstepMaxSteps = function () {
  12366. return this._lockstepMaxSteps;
  12367. };
  12368. /**
  12369. * Gets an object containing information about the current webGL context
  12370. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12371. */
  12372. Engine.prototype.getGlInfo = function () {
  12373. return {
  12374. vendor: this._glVendor,
  12375. renderer: this._glRenderer,
  12376. version: this._glVersion
  12377. };
  12378. };
  12379. /**
  12380. * Gets current aspect ratio
  12381. * @param camera defines the camera to use to get the aspect ratio
  12382. * @param useScreen defines if screen size must be used (or the current render target if any)
  12383. * @returns a number defining the aspect ratio
  12384. */
  12385. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12386. if (useScreen === void 0) { useScreen = false; }
  12387. var viewport = camera.viewport;
  12388. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12389. };
  12390. /**
  12391. * Gets the current render width
  12392. * @param useScreen defines if screen size must be used (or the current render target if any)
  12393. * @returns a number defining the current render width
  12394. */
  12395. Engine.prototype.getRenderWidth = function (useScreen) {
  12396. if (useScreen === void 0) { useScreen = false; }
  12397. if (!useScreen && this._currentRenderTarget) {
  12398. return this._currentRenderTarget.width;
  12399. }
  12400. return this._gl.drawingBufferWidth;
  12401. };
  12402. /**
  12403. * Gets the current render height
  12404. * @param useScreen defines if screen size must be used (or the current render target if any)
  12405. * @returns a number defining the current render height
  12406. */
  12407. Engine.prototype.getRenderHeight = function (useScreen) {
  12408. if (useScreen === void 0) { useScreen = false; }
  12409. if (!useScreen && this._currentRenderTarget) {
  12410. return this._currentRenderTarget.height;
  12411. }
  12412. return this._gl.drawingBufferHeight;
  12413. };
  12414. /**
  12415. * Gets the HTML canvas attached with the current webGL context
  12416. * @returns a HTML canvas
  12417. */
  12418. Engine.prototype.getRenderingCanvas = function () {
  12419. return this._renderingCanvas;
  12420. };
  12421. /**
  12422. * Gets the client rect of the HTML canvas attached with the current webGL context
  12423. * @returns a client rectanglee
  12424. */
  12425. Engine.prototype.getRenderingCanvasClientRect = function () {
  12426. if (!this._renderingCanvas) {
  12427. return null;
  12428. }
  12429. return this._renderingCanvas.getBoundingClientRect();
  12430. };
  12431. /**
  12432. * Defines the hardware scaling level.
  12433. * By default the hardware scaling level is computed from the window device ratio.
  12434. * 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.
  12435. * @param level defines the level to use
  12436. */
  12437. Engine.prototype.setHardwareScalingLevel = function (level) {
  12438. this._hardwareScalingLevel = level;
  12439. this.resize();
  12440. };
  12441. /**
  12442. * Gets the current hardware scaling level.
  12443. * By default the hardware scaling level is computed from the window device ratio.
  12444. * 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.
  12445. * @returns a number indicating the current hardware scaling level
  12446. */
  12447. Engine.prototype.getHardwareScalingLevel = function () {
  12448. return this._hardwareScalingLevel;
  12449. };
  12450. /**
  12451. * Gets the list of loaded textures
  12452. * @returns an array containing all loaded textures
  12453. */
  12454. Engine.prototype.getLoadedTexturesCache = function () {
  12455. return this._internalTexturesCache;
  12456. };
  12457. /**
  12458. * Gets the object containing all engine capabilities
  12459. * @returns the EngineCapabilities object
  12460. */
  12461. Engine.prototype.getCaps = function () {
  12462. return this._caps;
  12463. };
  12464. Object.defineProperty(Engine.prototype, "drawCalls", {
  12465. /** @hidden */
  12466. get: function () {
  12467. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12468. return 0;
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12474. /** @hidden */
  12475. get: function () {
  12476. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12477. return null;
  12478. },
  12479. enumerable: true,
  12480. configurable: true
  12481. });
  12482. /**
  12483. * Gets the current depth function
  12484. * @returns a number defining the depth function
  12485. */
  12486. Engine.prototype.getDepthFunction = function () {
  12487. return this._depthCullingState.depthFunc;
  12488. };
  12489. /**
  12490. * Sets the current depth function
  12491. * @param depthFunc defines the function to use
  12492. */
  12493. Engine.prototype.setDepthFunction = function (depthFunc) {
  12494. this._depthCullingState.depthFunc = depthFunc;
  12495. };
  12496. /**
  12497. * Sets the current depth function to GREATER
  12498. */
  12499. Engine.prototype.setDepthFunctionToGreater = function () {
  12500. this._depthCullingState.depthFunc = this._gl.GREATER;
  12501. };
  12502. /**
  12503. * Sets the current depth function to GEQUAL
  12504. */
  12505. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12506. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12507. };
  12508. /**
  12509. * Sets the current depth function to LESS
  12510. */
  12511. Engine.prototype.setDepthFunctionToLess = function () {
  12512. this._depthCullingState.depthFunc = this._gl.LESS;
  12513. };
  12514. /**
  12515. * Sets the current depth function to LEQUAL
  12516. */
  12517. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12518. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12519. };
  12520. /**
  12521. * Gets a boolean indicating if stencil buffer is enabled
  12522. * @returns the current stencil buffer state
  12523. */
  12524. Engine.prototype.getStencilBuffer = function () {
  12525. return this._stencilState.stencilTest;
  12526. };
  12527. /**
  12528. * Enable or disable the stencil buffer
  12529. * @param enable defines if the stencil buffer must be enabled or disabled
  12530. */
  12531. Engine.prototype.setStencilBuffer = function (enable) {
  12532. this._stencilState.stencilTest = enable;
  12533. };
  12534. /**
  12535. * Gets the current stencil mask
  12536. * @returns a number defining the new stencil mask to use
  12537. */
  12538. Engine.prototype.getStencilMask = function () {
  12539. return this._stencilState.stencilMask;
  12540. };
  12541. /**
  12542. * Sets the current stencil mask
  12543. * @param mask defines the new stencil mask to use
  12544. */
  12545. Engine.prototype.setStencilMask = function (mask) {
  12546. this._stencilState.stencilMask = mask;
  12547. };
  12548. /**
  12549. * Gets the current stencil function
  12550. * @returns a number defining the stencil function to use
  12551. */
  12552. Engine.prototype.getStencilFunction = function () {
  12553. return this._stencilState.stencilFunc;
  12554. };
  12555. /**
  12556. * Gets the current stencil reference value
  12557. * @returns a number defining the stencil reference value to use
  12558. */
  12559. Engine.prototype.getStencilFunctionReference = function () {
  12560. return this._stencilState.stencilFuncRef;
  12561. };
  12562. /**
  12563. * Gets the current stencil mask
  12564. * @returns a number defining the stencil mask to use
  12565. */
  12566. Engine.prototype.getStencilFunctionMask = function () {
  12567. return this._stencilState.stencilFuncMask;
  12568. };
  12569. /**
  12570. * Sets the current stencil function
  12571. * @param stencilFunc defines the new stencil function to use
  12572. */
  12573. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12574. this._stencilState.stencilFunc = stencilFunc;
  12575. };
  12576. /**
  12577. * Sets the current stencil reference
  12578. * @param reference defines the new stencil reference to use
  12579. */
  12580. Engine.prototype.setStencilFunctionReference = function (reference) {
  12581. this._stencilState.stencilFuncRef = reference;
  12582. };
  12583. /**
  12584. * Sets the current stencil mask
  12585. * @param mask defines the new stencil mask to use
  12586. */
  12587. Engine.prototype.setStencilFunctionMask = function (mask) {
  12588. this._stencilState.stencilFuncMask = mask;
  12589. };
  12590. /**
  12591. * Gets the current stencil operation when stencil fails
  12592. * @returns a number defining stencil operation to use when stencil fails
  12593. */
  12594. Engine.prototype.getStencilOperationFail = function () {
  12595. return this._stencilState.stencilOpStencilFail;
  12596. };
  12597. /**
  12598. * Gets the current stencil operation when depth fails
  12599. * @returns a number defining stencil operation to use when depth fails
  12600. */
  12601. Engine.prototype.getStencilOperationDepthFail = function () {
  12602. return this._stencilState.stencilOpDepthFail;
  12603. };
  12604. /**
  12605. * Gets the current stencil operation when stencil passes
  12606. * @returns a number defining stencil operation to use when stencil passes
  12607. */
  12608. Engine.prototype.getStencilOperationPass = function () {
  12609. return this._stencilState.stencilOpStencilDepthPass;
  12610. };
  12611. /**
  12612. * Sets the stencil operation to use when stencil fails
  12613. * @param operation defines the stencil operation to use when stencil fails
  12614. */
  12615. Engine.prototype.setStencilOperationFail = function (operation) {
  12616. this._stencilState.stencilOpStencilFail = operation;
  12617. };
  12618. /**
  12619. * Sets the stencil operation to use when depth fails
  12620. * @param operation defines the stencil operation to use when depth fails
  12621. */
  12622. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12623. this._stencilState.stencilOpDepthFail = operation;
  12624. };
  12625. /**
  12626. * Sets the stencil operation to use when stencil passes
  12627. * @param operation defines the stencil operation to use when stencil passes
  12628. */
  12629. Engine.prototype.setStencilOperationPass = function (operation) {
  12630. this._stencilState.stencilOpStencilDepthPass = operation;
  12631. };
  12632. /**
  12633. * Sets a boolean indicating if the dithering state is enabled or disabled
  12634. * @param value defines the dithering state
  12635. */
  12636. Engine.prototype.setDitheringState = function (value) {
  12637. if (value) {
  12638. this._gl.enable(this._gl.DITHER);
  12639. }
  12640. else {
  12641. this._gl.disable(this._gl.DITHER);
  12642. }
  12643. };
  12644. /**
  12645. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12646. * @param value defines the rasterizer state
  12647. */
  12648. Engine.prototype.setRasterizerState = function (value) {
  12649. if (value) {
  12650. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12651. }
  12652. else {
  12653. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12654. }
  12655. };
  12656. /**
  12657. * stop executing a render loop function and remove it from the execution array
  12658. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12659. */
  12660. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12661. if (!renderFunction) {
  12662. this._activeRenderLoops = [];
  12663. return;
  12664. }
  12665. var index = this._activeRenderLoops.indexOf(renderFunction);
  12666. if (index >= 0) {
  12667. this._activeRenderLoops.splice(index, 1);
  12668. }
  12669. };
  12670. /** @hidden */
  12671. Engine.prototype._renderLoop = function () {
  12672. if (!this._contextWasLost) {
  12673. var shouldRender = true;
  12674. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12675. shouldRender = false;
  12676. }
  12677. if (shouldRender) {
  12678. // Start new frame
  12679. this.beginFrame();
  12680. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12681. var renderFunction = this._activeRenderLoops[index];
  12682. renderFunction();
  12683. }
  12684. // Present
  12685. this.endFrame();
  12686. }
  12687. }
  12688. if (this._activeRenderLoops.length > 0) {
  12689. // Register new frame
  12690. var requester = null;
  12691. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12692. requester = this._vrDisplay;
  12693. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12694. }
  12695. else {
  12696. this._renderingQueueLaunched = false;
  12697. }
  12698. };
  12699. /**
  12700. * Register and execute a render loop. The engine can have more than one render function
  12701. * @param renderFunction defines the function to continuously execute
  12702. */
  12703. Engine.prototype.runRenderLoop = function (renderFunction) {
  12704. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12705. return;
  12706. }
  12707. this._activeRenderLoops.push(renderFunction);
  12708. if (!this._renderingQueueLaunched) {
  12709. this._renderingQueueLaunched = true;
  12710. this._bindedRenderFunction = this._renderLoop.bind(this);
  12711. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12712. }
  12713. };
  12714. /**
  12715. * Toggle full screen mode
  12716. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12717. * @param options defines an option object to be sent to the requestFullscreen function
  12718. */
  12719. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12720. if (this.isFullscreen) {
  12721. BABYLON.Tools.ExitFullscreen();
  12722. }
  12723. else {
  12724. this._pointerLockRequested = requestPointerLock;
  12725. if (this._renderingCanvas) {
  12726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12727. }
  12728. }
  12729. };
  12730. /**
  12731. * Clear the current render buffer or the current render target (if any is set up)
  12732. * @param color defines the color to use
  12733. * @param backBuffer defines if the back buffer must be cleared
  12734. * @param depth defines if the depth buffer must be cleared
  12735. * @param stencil defines if the stencil buffer must be cleared
  12736. */
  12737. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12738. if (stencil === void 0) { stencil = false; }
  12739. this.applyStates();
  12740. var mode = 0;
  12741. if (backBuffer && color) {
  12742. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12743. mode |= this._gl.COLOR_BUFFER_BIT;
  12744. }
  12745. if (depth) {
  12746. this._gl.clearDepth(1.0);
  12747. mode |= this._gl.DEPTH_BUFFER_BIT;
  12748. }
  12749. if (stencil) {
  12750. this._gl.clearStencil(0);
  12751. mode |= this._gl.STENCIL_BUFFER_BIT;
  12752. }
  12753. this._gl.clear(mode);
  12754. };
  12755. /**
  12756. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12757. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12758. * @param y defines the y-coordinate of the corner of the clear rectangle
  12759. * @param width defines the width of the clear rectangle
  12760. * @param height defines the height of the clear rectangle
  12761. * @param clearColor defines the clear color
  12762. */
  12763. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12764. var gl = this._gl;
  12765. // Save state
  12766. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12767. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12768. // Change state
  12769. gl.enable(gl.SCISSOR_TEST);
  12770. gl.scissor(x, y, width, height);
  12771. // Clear
  12772. this.clear(clearColor, true, true, true);
  12773. // Restore state
  12774. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12775. if (curScissor === true) {
  12776. gl.enable(gl.SCISSOR_TEST);
  12777. }
  12778. else {
  12779. gl.disable(gl.SCISSOR_TEST);
  12780. }
  12781. };
  12782. /**
  12783. * Set the WebGL's viewport
  12784. * @param viewport defines the viewport element to be used
  12785. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12786. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12787. */
  12788. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12789. var width = requiredWidth || this.getRenderWidth();
  12790. var height = requiredHeight || this.getRenderHeight();
  12791. var x = viewport.x || 0;
  12792. var y = viewport.y || 0;
  12793. this._cachedViewport = viewport;
  12794. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12795. };
  12796. /**
  12797. * Directly set the WebGL Viewport
  12798. * @param x defines the x coordinate of the viewport (in screen space)
  12799. * @param y defines the y coordinate of the viewport (in screen space)
  12800. * @param width defines the width of the viewport (in screen space)
  12801. * @param height defines the height of the viewport (in screen space)
  12802. * @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
  12803. */
  12804. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12805. var currentViewport = this._cachedViewport;
  12806. this._cachedViewport = null;
  12807. this._gl.viewport(x, y, width, height);
  12808. return currentViewport;
  12809. };
  12810. /**
  12811. * Begin a new frame
  12812. */
  12813. Engine.prototype.beginFrame = function () {
  12814. this.onBeginFrameObservable.notifyObservers(this);
  12815. this._measureFps();
  12816. };
  12817. /**
  12818. * Enf the current frame
  12819. */
  12820. Engine.prototype.endFrame = function () {
  12821. // Force a flush in case we are using a bad OS.
  12822. if (this._badOS) {
  12823. this.flushFramebuffer();
  12824. }
  12825. // Submit frame to the vr device, if enabled
  12826. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12827. // TODO: We should only submit the frame if we read frameData successfully.
  12828. this._vrDisplay.submitFrame();
  12829. }
  12830. this.onEndFrameObservable.notifyObservers(this);
  12831. };
  12832. /**
  12833. * Resize the view according to the canvas' size
  12834. */
  12835. Engine.prototype.resize = function () {
  12836. // We're not resizing the size of the canvas while in VR mode & presenting
  12837. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12838. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12839. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12840. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12841. }
  12842. };
  12843. /**
  12844. * Force a specific size of the canvas
  12845. * @param width defines the new canvas' width
  12846. * @param height defines the new canvas' height
  12847. */
  12848. Engine.prototype.setSize = function (width, height) {
  12849. if (!this._renderingCanvas) {
  12850. return;
  12851. }
  12852. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12853. return;
  12854. }
  12855. this._renderingCanvas.width = width;
  12856. this._renderingCanvas.height = height;
  12857. for (var index = 0; index < this.scenes.length; index++) {
  12858. var scene = this.scenes[index];
  12859. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12860. var cam = scene.cameras[camIndex];
  12861. cam._currentRenderId = 0;
  12862. }
  12863. }
  12864. if (this.onResizeObservable.hasObservers) {
  12865. this.onResizeObservable.notifyObservers(this);
  12866. }
  12867. };
  12868. // WebVR functions
  12869. /**
  12870. * Gets a boolean indicating if a webVR device was detected
  12871. * @returns true if a webVR device was detected
  12872. */
  12873. Engine.prototype.isVRDevicePresent = function () {
  12874. return !!this._vrDisplay;
  12875. };
  12876. /**
  12877. * Gets the current webVR device
  12878. * @returns the current webVR device (or null)
  12879. */
  12880. Engine.prototype.getVRDevice = function () {
  12881. return this._vrDisplay;
  12882. };
  12883. /**
  12884. * Initializes a webVR display and starts listening to display change events
  12885. * The onVRDisplayChangedObservable will be notified upon these changes
  12886. * @returns The onVRDisplayChangedObservable
  12887. */
  12888. Engine.prototype.initWebVR = function () {
  12889. this.initWebVRAsync();
  12890. return this.onVRDisplayChangedObservable;
  12891. };
  12892. /**
  12893. * Initializes a webVR display and starts listening to display change events
  12894. * The onVRDisplayChangedObservable will be notified upon these changes
  12895. * @returns A promise containing a VRDisplay and if vr is supported
  12896. */
  12897. Engine.prototype.initWebVRAsync = function () {
  12898. var _this = this;
  12899. var notifyObservers = function () {
  12900. var eventArgs = {
  12901. vrDisplay: _this._vrDisplay,
  12902. vrSupported: _this._vrSupported
  12903. };
  12904. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12905. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12906. };
  12907. if (!this._onVrDisplayConnect) {
  12908. this._onVrDisplayConnect = function (event) {
  12909. _this._vrDisplay = event.display;
  12910. notifyObservers();
  12911. };
  12912. this._onVrDisplayDisconnect = function () {
  12913. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12914. _this._vrDisplay = undefined;
  12915. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12916. notifyObservers();
  12917. };
  12918. this._onVrDisplayPresentChange = function () {
  12919. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12920. };
  12921. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12922. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12923. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12924. }
  12925. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12926. this._webVRInitPromise.then(notifyObservers);
  12927. return this._webVRInitPromise;
  12928. };
  12929. /**
  12930. * Call this function to switch to webVR mode
  12931. * Will do nothing if webVR is not supported or if there is no webVR device
  12932. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12933. */
  12934. Engine.prototype.enableVR = function () {
  12935. var _this = this;
  12936. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12937. var onResolved = function () {
  12938. _this.onVRRequestPresentComplete.notifyObservers(true);
  12939. _this._onVRFullScreenTriggered();
  12940. };
  12941. var onRejected = function () {
  12942. _this.onVRRequestPresentComplete.notifyObservers(false);
  12943. };
  12944. this.onVRRequestPresentStart.notifyObservers(this);
  12945. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12946. }
  12947. };
  12948. /**
  12949. * Call this function to leave webVR mode
  12950. * Will do nothing if webVR is not supported or if there is no webVR device
  12951. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12952. */
  12953. Engine.prototype.disableVR = function () {
  12954. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12955. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12956. }
  12957. };
  12958. Engine.prototype._getVRDisplaysAsync = function () {
  12959. var _this = this;
  12960. return new Promise(function (res, rej) {
  12961. if (navigator.getVRDisplays) {
  12962. navigator.getVRDisplays().then(function (devices) {
  12963. _this._vrSupported = true;
  12964. // note that devices may actually be an empty array. This is fine;
  12965. // we expect this._vrDisplay to be undefined in this case.
  12966. _this._vrDisplay = devices[0];
  12967. res({
  12968. vrDisplay: _this._vrDisplay,
  12969. vrSupported: _this._vrSupported
  12970. });
  12971. });
  12972. }
  12973. else {
  12974. _this._vrDisplay = undefined;
  12975. _this._vrSupported = false;
  12976. res({
  12977. vrDisplay: _this._vrDisplay,
  12978. vrSupported: _this._vrSupported
  12979. });
  12980. }
  12981. });
  12982. };
  12983. /**
  12984. * Binds the frame buffer to the specified texture.
  12985. * @param texture The texture to render to or null for the default canvas
  12986. * @param faceIndex The face of the texture to render to in case of cube texture
  12987. * @param requiredWidth The width of the target to render to
  12988. * @param requiredHeight The height of the target to render to
  12989. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12990. * @param depthStencilTexture The depth stencil texture to use to render
  12991. */
  12992. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12993. if (this._currentRenderTarget) {
  12994. this.unBindFramebuffer(this._currentRenderTarget);
  12995. }
  12996. this._currentRenderTarget = texture;
  12997. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12998. var gl = this._gl;
  12999. if (texture.isCube) {
  13000. if (faceIndex === undefined) {
  13001. faceIndex = 0;
  13002. }
  13003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13004. if (depthStencilTexture) {
  13005. if (depthStencilTexture._generateStencilBuffer) {
  13006. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13007. }
  13008. else {
  13009. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13010. }
  13011. }
  13012. }
  13013. if (this._cachedViewport && !forceFullscreenViewport) {
  13014. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13015. }
  13016. else {
  13017. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13018. }
  13019. this.wipeCaches();
  13020. };
  13021. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13022. if (this._currentFramebuffer !== framebuffer) {
  13023. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13024. this._currentFramebuffer = framebuffer;
  13025. }
  13026. };
  13027. /**
  13028. * Unbind the current render target texture from the webGL context
  13029. * @param texture defines the render target texture to unbind
  13030. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13031. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13032. */
  13033. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13034. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13035. this._currentRenderTarget = null;
  13036. // If MSAA, we need to bitblt back to main texture
  13037. var gl = this._gl;
  13038. if (texture._MSAAFramebuffer) {
  13039. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13040. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13041. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13042. }
  13043. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13044. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13045. gl.generateMipmap(gl.TEXTURE_2D);
  13046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13047. }
  13048. if (onBeforeUnbind) {
  13049. if (texture._MSAAFramebuffer) {
  13050. // Bind the correct framebuffer
  13051. this.bindUnboundFramebuffer(texture._framebuffer);
  13052. }
  13053. onBeforeUnbind();
  13054. }
  13055. this.bindUnboundFramebuffer(null);
  13056. };
  13057. /**
  13058. * Unbind a list of render target textures from the webGL context
  13059. * This is used only when drawBuffer extension or webGL2 are active
  13060. * @param textures defines the render target textures to unbind
  13061. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13062. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13063. */
  13064. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13065. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13066. this._currentRenderTarget = null;
  13067. // If MSAA, we need to bitblt back to main texture
  13068. var gl = this._gl;
  13069. if (textures[0]._MSAAFramebuffer) {
  13070. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13071. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13072. var attachments = textures[0]._attachments;
  13073. if (!attachments) {
  13074. attachments = new Array(textures.length);
  13075. textures[0]._attachments = attachments;
  13076. }
  13077. for (var i = 0; i < textures.length; i++) {
  13078. var texture = textures[i];
  13079. for (var j = 0; j < attachments.length; j++) {
  13080. attachments[j] = gl.NONE;
  13081. }
  13082. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13083. gl.readBuffer(attachments[i]);
  13084. gl.drawBuffers(attachments);
  13085. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13086. }
  13087. for (var i = 0; i < attachments.length; i++) {
  13088. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13089. }
  13090. gl.drawBuffers(attachments);
  13091. }
  13092. for (var i = 0; i < textures.length; i++) {
  13093. var texture = textures[i];
  13094. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13095. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13096. gl.generateMipmap(gl.TEXTURE_2D);
  13097. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13098. }
  13099. }
  13100. if (onBeforeUnbind) {
  13101. if (textures[0]._MSAAFramebuffer) {
  13102. // Bind the correct framebuffer
  13103. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13104. }
  13105. onBeforeUnbind();
  13106. }
  13107. this.bindUnboundFramebuffer(null);
  13108. };
  13109. /**
  13110. * Force the mipmap generation for the given render target texture
  13111. * @param texture defines the render target texture to use
  13112. */
  13113. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13114. if (texture.generateMipMaps) {
  13115. var gl = this._gl;
  13116. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13117. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13118. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13119. }
  13120. };
  13121. /**
  13122. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13123. */
  13124. Engine.prototype.flushFramebuffer = function () {
  13125. this._gl.flush();
  13126. };
  13127. /**
  13128. * Unbind the current render target and bind the default framebuffer
  13129. */
  13130. Engine.prototype.restoreDefaultFramebuffer = function () {
  13131. if (this._currentRenderTarget) {
  13132. this.unBindFramebuffer(this._currentRenderTarget);
  13133. }
  13134. else {
  13135. this.bindUnboundFramebuffer(null);
  13136. }
  13137. if (this._cachedViewport) {
  13138. this.setViewport(this._cachedViewport);
  13139. }
  13140. this.wipeCaches();
  13141. };
  13142. // UBOs
  13143. /**
  13144. * Create an uniform buffer
  13145. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13146. * @param elements defines the content of the uniform buffer
  13147. * @returns the webGL uniform buffer
  13148. */
  13149. Engine.prototype.createUniformBuffer = function (elements) {
  13150. var ubo = this._gl.createBuffer();
  13151. if (!ubo) {
  13152. throw new Error("Unable to create uniform buffer");
  13153. }
  13154. this.bindUniformBuffer(ubo);
  13155. if (elements instanceof Float32Array) {
  13156. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13157. }
  13158. else {
  13159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13160. }
  13161. this.bindUniformBuffer(null);
  13162. ubo.references = 1;
  13163. return ubo;
  13164. };
  13165. /**
  13166. * Create a dynamic uniform buffer
  13167. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13168. * @param elements defines the content of the uniform buffer
  13169. * @returns the webGL uniform buffer
  13170. */
  13171. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13172. var ubo = this._gl.createBuffer();
  13173. if (!ubo) {
  13174. throw new Error("Unable to create dynamic uniform buffer");
  13175. }
  13176. this.bindUniformBuffer(ubo);
  13177. if (elements instanceof Float32Array) {
  13178. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13179. }
  13180. else {
  13181. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13182. }
  13183. this.bindUniformBuffer(null);
  13184. ubo.references = 1;
  13185. return ubo;
  13186. };
  13187. /**
  13188. * Update an existing uniform buffer
  13189. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13190. * @param uniformBuffer defines the target uniform buffer
  13191. * @param elements defines the content to update
  13192. * @param offset defines the offset in the uniform buffer where update should start
  13193. * @param count defines the size of the data to update
  13194. */
  13195. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13196. this.bindUniformBuffer(uniformBuffer);
  13197. if (offset === undefined) {
  13198. offset = 0;
  13199. }
  13200. if (count === undefined) {
  13201. if (elements instanceof Float32Array) {
  13202. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13203. }
  13204. else {
  13205. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13206. }
  13207. }
  13208. else {
  13209. if (elements instanceof Float32Array) {
  13210. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13211. }
  13212. else {
  13213. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13214. }
  13215. }
  13216. this.bindUniformBuffer(null);
  13217. };
  13218. // VBOs
  13219. Engine.prototype._resetVertexBufferBinding = function () {
  13220. this.bindArrayBuffer(null);
  13221. this._cachedVertexBuffers = null;
  13222. };
  13223. /**
  13224. * Creates a vertex buffer
  13225. * @param data the data for the vertex buffer
  13226. * @returns the new WebGL static buffer
  13227. */
  13228. Engine.prototype.createVertexBuffer = function (data) {
  13229. var vbo = this._gl.createBuffer();
  13230. if (!vbo) {
  13231. throw new Error("Unable to create vertex buffer");
  13232. }
  13233. this.bindArrayBuffer(vbo);
  13234. if (data instanceof Array) {
  13235. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13236. }
  13237. else {
  13238. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13239. }
  13240. this._resetVertexBufferBinding();
  13241. vbo.references = 1;
  13242. return vbo;
  13243. };
  13244. /**
  13245. * Creates a dynamic vertex buffer
  13246. * @param data the data for the dynamic vertex buffer
  13247. * @returns the new WebGL dynamic buffer
  13248. */
  13249. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13250. var vbo = this._gl.createBuffer();
  13251. if (!vbo) {
  13252. throw new Error("Unable to create dynamic vertex buffer");
  13253. }
  13254. this.bindArrayBuffer(vbo);
  13255. if (data instanceof Array) {
  13256. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13257. }
  13258. else {
  13259. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13260. }
  13261. this._resetVertexBufferBinding();
  13262. vbo.references = 1;
  13263. return vbo;
  13264. };
  13265. /**
  13266. * Update a dynamic index buffer
  13267. * @param indexBuffer defines the target index buffer
  13268. * @param indices defines the data to update
  13269. * @param offset defines the offset in the target index buffer where update should start
  13270. */
  13271. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13272. if (offset === void 0) { offset = 0; }
  13273. // Force cache update
  13274. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13275. this.bindIndexBuffer(indexBuffer);
  13276. var arrayBuffer;
  13277. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13278. arrayBuffer = indices;
  13279. }
  13280. else {
  13281. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13282. }
  13283. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13284. this._resetIndexBufferBinding();
  13285. };
  13286. /**
  13287. * Updates a dynamic vertex buffer.
  13288. * @param vertexBuffer the vertex buffer to update
  13289. * @param data the data used to update the vertex buffer
  13290. * @param byteOffset the byte offset of the data
  13291. * @param byteLength the byte length of the data
  13292. */
  13293. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13294. this.bindArrayBuffer(vertexBuffer);
  13295. if (byteOffset === undefined) {
  13296. byteOffset = 0;
  13297. }
  13298. if (byteLength === undefined) {
  13299. if (data instanceof Array) {
  13300. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13301. }
  13302. else {
  13303. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13304. }
  13305. }
  13306. else {
  13307. if (data instanceof Array) {
  13308. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13309. }
  13310. else {
  13311. if (data instanceof ArrayBuffer) {
  13312. data = new Uint8Array(data, byteOffset, byteLength);
  13313. }
  13314. else {
  13315. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13316. }
  13317. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13318. }
  13319. }
  13320. this._resetVertexBufferBinding();
  13321. };
  13322. Engine.prototype._resetIndexBufferBinding = function () {
  13323. this.bindIndexBuffer(null);
  13324. this._cachedIndexBuffer = null;
  13325. };
  13326. /**
  13327. * Creates a new index buffer
  13328. * @param indices defines the content of the index buffer
  13329. * @param updatable defines if the index buffer must be updatable
  13330. * @returns a new webGL buffer
  13331. */
  13332. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13333. var vbo = this._gl.createBuffer();
  13334. if (!vbo) {
  13335. throw new Error("Unable to create index buffer");
  13336. }
  13337. this.bindIndexBuffer(vbo);
  13338. // Check for 32 bits indices
  13339. var arrayBuffer;
  13340. var need32Bits = false;
  13341. if (indices instanceof Uint16Array) {
  13342. arrayBuffer = indices;
  13343. }
  13344. else {
  13345. //check 32 bit support
  13346. if (this._caps.uintIndices) {
  13347. if (indices instanceof Uint32Array) {
  13348. arrayBuffer = indices;
  13349. need32Bits = true;
  13350. }
  13351. else {
  13352. //number[] or Int32Array, check if 32 bit is necessary
  13353. for (var index = 0; index < indices.length; index++) {
  13354. if (indices[index] > 65535) {
  13355. need32Bits = true;
  13356. break;
  13357. }
  13358. }
  13359. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13360. }
  13361. }
  13362. else {
  13363. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13364. arrayBuffer = new Uint16Array(indices);
  13365. }
  13366. }
  13367. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13368. this._resetIndexBufferBinding();
  13369. vbo.references = 1;
  13370. vbo.is32Bits = need32Bits;
  13371. return vbo;
  13372. };
  13373. /**
  13374. * Bind a webGL buffer to the webGL context
  13375. * @param buffer defines the buffer to bind
  13376. */
  13377. Engine.prototype.bindArrayBuffer = function (buffer) {
  13378. if (!this._vaoRecordInProgress) {
  13379. this._unbindVertexArrayObject();
  13380. }
  13381. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13382. };
  13383. /**
  13384. * Bind an uniform buffer to the current webGL context
  13385. * @param buffer defines the buffer to bind
  13386. */
  13387. Engine.prototype.bindUniformBuffer = function (buffer) {
  13388. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13389. };
  13390. /**
  13391. * Bind a buffer to the current webGL context at a given location
  13392. * @param buffer defines the buffer to bind
  13393. * @param location defines the index where to bind the buffer
  13394. */
  13395. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13396. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13397. };
  13398. /**
  13399. * Bind a specific block at a given index in a specific shader program
  13400. * @param shaderProgram defines the shader program
  13401. * @param blockName defines the block name
  13402. * @param index defines the index where to bind the block
  13403. */
  13404. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13405. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13406. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13407. };
  13408. ;
  13409. Engine.prototype.bindIndexBuffer = function (buffer) {
  13410. if (!this._vaoRecordInProgress) {
  13411. this._unbindVertexArrayObject();
  13412. }
  13413. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13414. };
  13415. Engine.prototype.bindBuffer = function (buffer, target) {
  13416. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13417. this._gl.bindBuffer(target, buffer);
  13418. this._currentBoundBuffer[target] = buffer;
  13419. }
  13420. };
  13421. /**
  13422. * update the bound buffer with the given data
  13423. * @param data defines the data to update
  13424. */
  13425. Engine.prototype.updateArrayBuffer = function (data) {
  13426. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13427. };
  13428. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13429. var pointer = this._currentBufferPointers[indx];
  13430. var changed = false;
  13431. if (!pointer.active) {
  13432. changed = true;
  13433. pointer.active = true;
  13434. pointer.index = indx;
  13435. pointer.size = size;
  13436. pointer.type = type;
  13437. pointer.normalized = normalized;
  13438. pointer.stride = stride;
  13439. pointer.offset = offset;
  13440. pointer.buffer = buffer;
  13441. }
  13442. else {
  13443. if (pointer.buffer !== buffer) {
  13444. pointer.buffer = buffer;
  13445. changed = true;
  13446. }
  13447. if (pointer.size !== size) {
  13448. pointer.size = size;
  13449. changed = true;
  13450. }
  13451. if (pointer.type !== type) {
  13452. pointer.type = type;
  13453. changed = true;
  13454. }
  13455. if (pointer.normalized !== normalized) {
  13456. pointer.normalized = normalized;
  13457. changed = true;
  13458. }
  13459. if (pointer.stride !== stride) {
  13460. pointer.stride = stride;
  13461. changed = true;
  13462. }
  13463. if (pointer.offset !== offset) {
  13464. pointer.offset = offset;
  13465. changed = true;
  13466. }
  13467. }
  13468. if (changed || this._vaoRecordInProgress) {
  13469. this.bindArrayBuffer(buffer);
  13470. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13471. }
  13472. };
  13473. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13474. if (indexBuffer == null) {
  13475. return;
  13476. }
  13477. if (this._cachedIndexBuffer !== indexBuffer) {
  13478. this._cachedIndexBuffer = indexBuffer;
  13479. this.bindIndexBuffer(indexBuffer);
  13480. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13481. }
  13482. };
  13483. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13484. var attributes = effect.getAttributesNames();
  13485. if (!this._vaoRecordInProgress) {
  13486. this._unbindVertexArrayObject();
  13487. }
  13488. this.unbindAllAttributes();
  13489. for (var index = 0; index < attributes.length; index++) {
  13490. var order = effect.getAttributeLocation(index);
  13491. if (order >= 0) {
  13492. var vertexBuffer = vertexBuffers[attributes[index]];
  13493. if (!vertexBuffer) {
  13494. continue;
  13495. }
  13496. this._gl.enableVertexAttribArray(order);
  13497. if (!this._vaoRecordInProgress) {
  13498. this._vertexAttribArraysEnabled[order] = true;
  13499. }
  13500. var buffer = vertexBuffer.getBuffer();
  13501. if (buffer) {
  13502. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13503. if (vertexBuffer.getIsInstanced()) {
  13504. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13505. if (!this._vaoRecordInProgress) {
  13506. this._currentInstanceLocations.push(order);
  13507. this._currentInstanceBuffers.push(buffer);
  13508. }
  13509. }
  13510. }
  13511. }
  13512. }
  13513. };
  13514. /**
  13515. * Records a vertex array object
  13516. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13517. * @param vertexBuffers defines the list of vertex buffers to store
  13518. * @param indexBuffer defines the index buffer to store
  13519. * @param effect defines the effect to store
  13520. * @returns the new vertex array object
  13521. */
  13522. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13523. var vao = this._gl.createVertexArray();
  13524. this._vaoRecordInProgress = true;
  13525. this._gl.bindVertexArray(vao);
  13526. this._mustWipeVertexAttributes = true;
  13527. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13528. this.bindIndexBuffer(indexBuffer);
  13529. this._vaoRecordInProgress = false;
  13530. this._gl.bindVertexArray(null);
  13531. return vao;
  13532. };
  13533. /**
  13534. * Bind a specific vertex array object
  13535. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13536. * @param vertexArrayObject defines the vertex array object to bind
  13537. * @param indexBuffer defines the index buffer to bind
  13538. */
  13539. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13540. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13541. this._cachedVertexArrayObject = vertexArrayObject;
  13542. this._gl.bindVertexArray(vertexArrayObject);
  13543. this._cachedVertexBuffers = null;
  13544. this._cachedIndexBuffer = null;
  13545. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13546. this._mustWipeVertexAttributes = true;
  13547. }
  13548. };
  13549. /**
  13550. * Bind webGl buffers directly to the webGL context
  13551. * @param vertexBuffer defines the vertex buffer to bind
  13552. * @param indexBuffer defines the index buffer to bind
  13553. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13554. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13555. * @param effect defines the effect associated with the vertex buffer
  13556. */
  13557. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13558. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13559. this._cachedVertexBuffers = vertexBuffer;
  13560. this._cachedEffectForVertexBuffers = effect;
  13561. var attributesCount = effect.getAttributesCount();
  13562. this._unbindVertexArrayObject();
  13563. this.unbindAllAttributes();
  13564. var offset = 0;
  13565. for (var index = 0; index < attributesCount; index++) {
  13566. if (index < vertexDeclaration.length) {
  13567. var order = effect.getAttributeLocation(index);
  13568. if (order >= 0) {
  13569. this._gl.enableVertexAttribArray(order);
  13570. this._vertexAttribArraysEnabled[order] = true;
  13571. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13572. }
  13573. offset += vertexDeclaration[index] * 4;
  13574. }
  13575. }
  13576. }
  13577. this._bindIndexBufferWithCache(indexBuffer);
  13578. };
  13579. Engine.prototype._unbindVertexArrayObject = function () {
  13580. if (!this._cachedVertexArrayObject) {
  13581. return;
  13582. }
  13583. this._cachedVertexArrayObject = null;
  13584. this._gl.bindVertexArray(null);
  13585. };
  13586. /**
  13587. * Bind a list of vertex buffers to the webGL context
  13588. * @param vertexBuffers defines the list of vertex buffers to bind
  13589. * @param indexBuffer defines the index buffer to bind
  13590. * @param effect defines the effect associated with the vertex buffers
  13591. */
  13592. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13593. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13594. this._cachedVertexBuffers = vertexBuffers;
  13595. this._cachedEffectForVertexBuffers = effect;
  13596. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13597. }
  13598. this._bindIndexBufferWithCache(indexBuffer);
  13599. };
  13600. /**
  13601. * Unbind all instance attributes
  13602. */
  13603. Engine.prototype.unbindInstanceAttributes = function () {
  13604. var boundBuffer;
  13605. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13606. var instancesBuffer = this._currentInstanceBuffers[i];
  13607. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13608. boundBuffer = instancesBuffer;
  13609. this.bindArrayBuffer(instancesBuffer);
  13610. }
  13611. var offsetLocation = this._currentInstanceLocations[i];
  13612. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13613. }
  13614. this._currentInstanceBuffers.length = 0;
  13615. this._currentInstanceLocations.length = 0;
  13616. };
  13617. /**
  13618. * Release and free the memory of a vertex array object
  13619. * @param vao defines the vertex array object to delete
  13620. */
  13621. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13622. this._gl.deleteVertexArray(vao);
  13623. };
  13624. /** @hidden */
  13625. Engine.prototype._releaseBuffer = function (buffer) {
  13626. buffer.references--;
  13627. if (buffer.references === 0) {
  13628. this._gl.deleteBuffer(buffer);
  13629. return true;
  13630. }
  13631. return false;
  13632. };
  13633. /**
  13634. * Creates a webGL buffer to use with instanciation
  13635. * @param capacity defines the size of the buffer
  13636. * @returns the webGL buffer
  13637. */
  13638. Engine.prototype.createInstancesBuffer = function (capacity) {
  13639. var buffer = this._gl.createBuffer();
  13640. if (!buffer) {
  13641. throw new Error("Unable to create instance buffer");
  13642. }
  13643. buffer.capacity = capacity;
  13644. this.bindArrayBuffer(buffer);
  13645. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13646. return buffer;
  13647. };
  13648. /**
  13649. * Delete a webGL buffer used with instanciation
  13650. * @param buffer defines the webGL buffer to delete
  13651. */
  13652. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13653. this._gl.deleteBuffer(buffer);
  13654. };
  13655. /**
  13656. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13657. * @param instancesBuffer defines the webGL buffer to update and bind
  13658. * @param data defines the data to store in the buffer
  13659. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13660. */
  13661. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13662. this.bindArrayBuffer(instancesBuffer);
  13663. if (data) {
  13664. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13665. }
  13666. if (offsetLocations[0].index !== undefined) {
  13667. var stride = 0;
  13668. for (var i = 0; i < offsetLocations.length; i++) {
  13669. var ai = offsetLocations[i];
  13670. stride += ai.attributeSize * 4;
  13671. }
  13672. for (var i = 0; i < offsetLocations.length; i++) {
  13673. var ai = offsetLocations[i];
  13674. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13675. this._gl.enableVertexAttribArray(ai.index);
  13676. this._vertexAttribArraysEnabled[ai.index] = true;
  13677. }
  13678. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13679. this._gl.vertexAttribDivisor(ai.index, 1);
  13680. this._currentInstanceLocations.push(ai.index);
  13681. this._currentInstanceBuffers.push(instancesBuffer);
  13682. }
  13683. }
  13684. else {
  13685. for (var index = 0; index < 4; index++) {
  13686. var offsetLocation = offsetLocations[index];
  13687. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13688. this._gl.enableVertexAttribArray(offsetLocation);
  13689. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13690. }
  13691. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13692. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13693. this._currentInstanceLocations.push(offsetLocation);
  13694. this._currentInstanceBuffers.push(instancesBuffer);
  13695. }
  13696. }
  13697. };
  13698. /**
  13699. * Apply all cached states (depth, culling, stencil and alpha)
  13700. */
  13701. Engine.prototype.applyStates = function () {
  13702. this._depthCullingState.apply(this._gl);
  13703. this._stencilState.apply(this._gl);
  13704. this._alphaState.apply(this._gl);
  13705. };
  13706. /**
  13707. * Send a draw order
  13708. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13709. * @param indexStart defines the starting index
  13710. * @param indexCount defines the number of index to draw
  13711. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13712. */
  13713. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13714. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13715. };
  13716. /**
  13717. * Draw a list of points
  13718. * @param verticesStart defines the index of first vertex to draw
  13719. * @param verticesCount defines the count of vertices to draw
  13720. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13721. */
  13722. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13723. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13724. };
  13725. /**
  13726. * Draw a list of unindexed primitives
  13727. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13728. * @param verticesStart defines the index of first vertex to draw
  13729. * @param verticesCount defines the count of vertices to draw
  13730. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13731. */
  13732. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13733. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13734. };
  13735. /**
  13736. * Draw a list of indexed primitives
  13737. * @param fillMode defines the primitive to use
  13738. * @param indexStart defines the starting index
  13739. * @param indexCount defines the number of index to draw
  13740. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13741. */
  13742. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13743. // Apply states
  13744. this.applyStates();
  13745. this._drawCalls.addCount(1, false);
  13746. // Render
  13747. var drawMode = this._drawMode(fillMode);
  13748. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13749. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13750. if (instancesCount) {
  13751. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13752. }
  13753. else {
  13754. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13755. }
  13756. };
  13757. /**
  13758. * Draw a list of unindexed primitives
  13759. * @param fillMode defines the primitive to use
  13760. * @param verticesStart defines the index of first vertex to draw
  13761. * @param verticesCount defines the count of vertices to draw
  13762. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13763. */
  13764. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13765. // Apply states
  13766. this.applyStates();
  13767. this._drawCalls.addCount(1, false);
  13768. var drawMode = this._drawMode(fillMode);
  13769. if (instancesCount) {
  13770. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13771. }
  13772. else {
  13773. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13774. }
  13775. };
  13776. Engine.prototype._drawMode = function (fillMode) {
  13777. switch (fillMode) {
  13778. // Triangle views
  13779. case BABYLON.Material.TriangleFillMode:
  13780. return this._gl.TRIANGLES;
  13781. case BABYLON.Material.PointFillMode:
  13782. return this._gl.POINTS;
  13783. case BABYLON.Material.WireFrameFillMode:
  13784. return this._gl.LINES;
  13785. // Draw modes
  13786. case BABYLON.Material.PointListDrawMode:
  13787. return this._gl.POINTS;
  13788. case BABYLON.Material.LineListDrawMode:
  13789. return this._gl.LINES;
  13790. case BABYLON.Material.LineLoopDrawMode:
  13791. return this._gl.LINE_LOOP;
  13792. case BABYLON.Material.LineStripDrawMode:
  13793. return this._gl.LINE_STRIP;
  13794. case BABYLON.Material.TriangleStripDrawMode:
  13795. return this._gl.TRIANGLE_STRIP;
  13796. case BABYLON.Material.TriangleFanDrawMode:
  13797. return this._gl.TRIANGLE_FAN;
  13798. default:
  13799. return this._gl.TRIANGLES;
  13800. }
  13801. };
  13802. // Shaders
  13803. /** @hidden */
  13804. Engine.prototype._releaseEffect = function (effect) {
  13805. if (this._compiledEffects[effect._key]) {
  13806. delete this._compiledEffects[effect._key];
  13807. this._deleteProgram(effect.getProgram());
  13808. }
  13809. };
  13810. /** @hidden */
  13811. Engine.prototype._deleteProgram = function (program) {
  13812. if (program) {
  13813. program.__SPECTOR_rebuildProgram = null;
  13814. if (program.transformFeedback) {
  13815. this.deleteTransformFeedback(program.transformFeedback);
  13816. program.transformFeedback = null;
  13817. }
  13818. this._gl.deleteProgram(program);
  13819. }
  13820. };
  13821. /**
  13822. * Create a new effect (used to store vertex/fragment shaders)
  13823. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13824. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13825. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13826. * @param samplers defines an array of string used to represent textures
  13827. * @param defines defines the string containing the defines to use to compile the shaders
  13828. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13829. * @param onCompiled defines a function to call when the effect creation is successful
  13830. * @param onError defines a function to call when the effect creation has failed
  13831. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13832. * @returns the new Effect
  13833. */
  13834. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13835. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13836. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13837. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13838. if (this._compiledEffects[name]) {
  13839. var compiledEffect = this._compiledEffects[name];
  13840. if (onCompiled && compiledEffect.isReady()) {
  13841. onCompiled(compiledEffect);
  13842. }
  13843. return compiledEffect;
  13844. }
  13845. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13846. effect._key = name;
  13847. this._compiledEffects[name] = effect;
  13848. return effect;
  13849. };
  13850. /**
  13851. * Create an effect to use with particle systems
  13852. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13853. * @param uniformsNames defines a list of attribute names
  13854. * @param samplers defines an array of string used to represent textures
  13855. * @param defines defines the string containing the defines to use to compile the shaders
  13856. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13857. * @param onCompiled defines a function to call when the effect creation is successful
  13858. * @param onError defines a function to call when the effect creation has failed
  13859. * @returns the new Effect
  13860. */
  13861. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13862. if (uniformsNames === void 0) { uniformsNames = []; }
  13863. if (samplers === void 0) { samplers = []; }
  13864. if (defines === void 0) { defines = ""; }
  13865. return this.createEffect({
  13866. vertex: "particles",
  13867. fragmentElement: fragmentName
  13868. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13869. };
  13870. /**
  13871. * Directly creates a webGL program
  13872. * @param vertexCode defines the vertex shader code to use
  13873. * @param fragmentCode defines the fragment shader code to use
  13874. * @param context defines the webGL context to use (if not set, the current one will be used)
  13875. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13876. * @returns the new webGL program
  13877. */
  13878. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13879. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13880. context = context || this._gl;
  13881. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13882. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13883. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13884. };
  13885. /**
  13886. * Creates a webGL program
  13887. * @param vertexCode defines the vertex shader code to use
  13888. * @param fragmentCode defines the fragment shader code to use
  13889. * @param defines defines the string containing the defines to use to compile the shaders
  13890. * @param context defines the webGL context to use (if not set, the current one will be used)
  13891. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13892. * @returns the new webGL program
  13893. */
  13894. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13895. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13896. context = context || this._gl;
  13897. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13898. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13899. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13900. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13901. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13902. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13903. return program;
  13904. };
  13905. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13906. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13907. var shaderProgram = context.createProgram();
  13908. if (!shaderProgram) {
  13909. throw new Error("Unable to create program");
  13910. }
  13911. context.attachShader(shaderProgram, vertexShader);
  13912. context.attachShader(shaderProgram, fragmentShader);
  13913. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13914. var transformFeedback = this.createTransformFeedback();
  13915. this.bindTransformFeedback(transformFeedback);
  13916. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13917. shaderProgram.transformFeedback = transformFeedback;
  13918. }
  13919. context.linkProgram(shaderProgram);
  13920. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13921. this.bindTransformFeedback(null);
  13922. }
  13923. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13924. if (!linked) {
  13925. context.validateProgram(shaderProgram);
  13926. var error = context.getProgramInfoLog(shaderProgram);
  13927. if (error) {
  13928. throw new Error(error);
  13929. }
  13930. }
  13931. context.deleteShader(vertexShader);
  13932. context.deleteShader(fragmentShader);
  13933. return shaderProgram;
  13934. };
  13935. /**
  13936. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13937. * @param shaderProgram defines the webGL program to use
  13938. * @param uniformsNames defines the list of uniform names
  13939. * @returns an array of webGL uniform locations
  13940. */
  13941. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13942. var results = new Array();
  13943. for (var index = 0; index < uniformsNames.length; index++) {
  13944. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13945. }
  13946. return results;
  13947. };
  13948. /**
  13949. * Gets the lsit of active attributes for a given webGL program
  13950. * @param shaderProgram defines the webGL program to use
  13951. * @param attributesNames defines the list of attribute names to get
  13952. * @returns an array of indices indicating the offset of each attribute
  13953. */
  13954. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13955. var results = [];
  13956. for (var index = 0; index < attributesNames.length; index++) {
  13957. try {
  13958. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13959. }
  13960. catch (e) {
  13961. results.push(-1);
  13962. }
  13963. }
  13964. return results;
  13965. };
  13966. /**
  13967. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13968. * @param effect defines the effect to activate
  13969. */
  13970. Engine.prototype.enableEffect = function (effect) {
  13971. if (!effect) {
  13972. return;
  13973. }
  13974. // Use program
  13975. this.bindSamplers(effect);
  13976. this._currentEffect = effect;
  13977. if (effect.onBind) {
  13978. effect.onBind(effect);
  13979. }
  13980. effect.onBindObservable.notifyObservers(effect);
  13981. };
  13982. /**
  13983. * Set the value of an uniform to an array of int32
  13984. * @param uniform defines the webGL uniform location where to store the value
  13985. * @param array defines the array of int32 to store
  13986. */
  13987. Engine.prototype.setIntArray = function (uniform, array) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform1iv(uniform, array);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to an array of int32 (stored as vec2)
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param array defines the array of int32 to store
  13996. */
  13997. Engine.prototype.setIntArray2 = function (uniform, array) {
  13998. if (!uniform || array.length % 2 !== 0)
  13999. return;
  14000. this._gl.uniform2iv(uniform, array);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to an array of int32 (stored as vec3)
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param array defines the array of int32 to store
  14006. */
  14007. Engine.prototype.setIntArray3 = function (uniform, array) {
  14008. if (!uniform || array.length % 3 !== 0)
  14009. return;
  14010. this._gl.uniform3iv(uniform, array);
  14011. };
  14012. /**
  14013. * Set the value of an uniform to an array of int32 (stored as vec4)
  14014. * @param uniform defines the webGL uniform location where to store the value
  14015. * @param array defines the array of int32 to store
  14016. */
  14017. Engine.prototype.setIntArray4 = function (uniform, array) {
  14018. if (!uniform || array.length % 4 !== 0)
  14019. return;
  14020. this._gl.uniform4iv(uniform, array);
  14021. };
  14022. /**
  14023. * Set the value of an uniform to an array of float32
  14024. * @param uniform defines the webGL uniform location where to store the value
  14025. * @param array defines the array of float32 to store
  14026. */
  14027. Engine.prototype.setFloatArray = function (uniform, array) {
  14028. if (!uniform)
  14029. return;
  14030. this._gl.uniform1fv(uniform, array);
  14031. };
  14032. /**
  14033. * Set the value of an uniform to an array of float32 (stored as vec2)
  14034. * @param uniform defines the webGL uniform location where to store the value
  14035. * @param array defines the array of float32 to store
  14036. */
  14037. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14038. if (!uniform || array.length % 2 !== 0)
  14039. return;
  14040. this._gl.uniform2fv(uniform, array);
  14041. };
  14042. /**
  14043. * Set the value of an uniform to an array of float32 (stored as vec3)
  14044. * @param uniform defines the webGL uniform location where to store the value
  14045. * @param array defines the array of float32 to store
  14046. */
  14047. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14048. if (!uniform || array.length % 3 !== 0)
  14049. return;
  14050. this._gl.uniform3fv(uniform, array);
  14051. };
  14052. /**
  14053. * Set the value of an uniform to an array of float32 (stored as vec4)
  14054. * @param uniform defines the webGL uniform location where to store the value
  14055. * @param array defines the array of float32 to store
  14056. */
  14057. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14058. if (!uniform || array.length % 4 !== 0)
  14059. return;
  14060. this._gl.uniform4fv(uniform, array);
  14061. };
  14062. /**
  14063. * Set the value of an uniform to an array of number
  14064. * @param uniform defines the webGL uniform location where to store the value
  14065. * @param array defines the array of number to store
  14066. */
  14067. Engine.prototype.setArray = function (uniform, array) {
  14068. if (!uniform)
  14069. return;
  14070. this._gl.uniform1fv(uniform, array);
  14071. };
  14072. /**
  14073. * Set the value of an uniform to an array of number (stored as vec2)
  14074. * @param uniform defines the webGL uniform location where to store the value
  14075. * @param array defines the array of number to store
  14076. */
  14077. Engine.prototype.setArray2 = function (uniform, array) {
  14078. if (!uniform || array.length % 2 !== 0)
  14079. return;
  14080. this._gl.uniform2fv(uniform, array);
  14081. };
  14082. /**
  14083. * Set the value of an uniform to an array of number (stored as vec3)
  14084. * @param uniform defines the webGL uniform location where to store the value
  14085. * @param array defines the array of number to store
  14086. */
  14087. Engine.prototype.setArray3 = function (uniform, array) {
  14088. if (!uniform || array.length % 3 !== 0)
  14089. return;
  14090. this._gl.uniform3fv(uniform, array);
  14091. };
  14092. /**
  14093. * Set the value of an uniform to an array of number (stored as vec4)
  14094. * @param uniform defines the webGL uniform location where to store the value
  14095. * @param array defines the array of number to store
  14096. */
  14097. Engine.prototype.setArray4 = function (uniform, array) {
  14098. if (!uniform || array.length % 4 !== 0)
  14099. return;
  14100. this._gl.uniform4fv(uniform, array);
  14101. };
  14102. /**
  14103. * Set the value of an uniform to an array of float32 (stored as matrices)
  14104. * @param uniform defines the webGL uniform location where to store the value
  14105. * @param matrices defines the array of float32 to store
  14106. */
  14107. Engine.prototype.setMatrices = function (uniform, matrices) {
  14108. if (!uniform)
  14109. return;
  14110. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14111. };
  14112. /**
  14113. * Set the value of an uniform to a matrix
  14114. * @param uniform defines the webGL uniform location where to store the value
  14115. * @param matrix defines the matrix to store
  14116. */
  14117. Engine.prototype.setMatrix = function (uniform, matrix) {
  14118. if (!uniform)
  14119. return;
  14120. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14121. };
  14122. /**
  14123. * Set the value of an uniform to a matrix (3x3)
  14124. * @param uniform defines the webGL uniform location where to store the value
  14125. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14126. */
  14127. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14128. if (!uniform)
  14129. return;
  14130. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14131. };
  14132. /**
  14133. * Set the value of an uniform to a matrix (2x2)
  14134. * @param uniform defines the webGL uniform location where to store the value
  14135. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14136. */
  14137. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14138. if (!uniform)
  14139. return;
  14140. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14141. };
  14142. /**
  14143. * Set the value of an uniform to a number (int)
  14144. * @param uniform defines the webGL uniform location where to store the value
  14145. * @param value defines the int number to store
  14146. */
  14147. Engine.prototype.setInt = function (uniform, value) {
  14148. if (!uniform)
  14149. return;
  14150. this._gl.uniform1i(uniform, value);
  14151. };
  14152. /**
  14153. * Set the value of an uniform to a number (float)
  14154. * @param uniform defines the webGL uniform location where to store the value
  14155. * @param value defines the float number to store
  14156. */
  14157. Engine.prototype.setFloat = function (uniform, value) {
  14158. if (!uniform)
  14159. return;
  14160. this._gl.uniform1f(uniform, value);
  14161. };
  14162. /**
  14163. * Set the value of an uniform to a vec2
  14164. * @param uniform defines the webGL uniform location where to store the value
  14165. * @param x defines the 1st component of the value
  14166. * @param y defines the 2nd component of the value
  14167. */
  14168. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14169. if (!uniform)
  14170. return;
  14171. this._gl.uniform2f(uniform, x, y);
  14172. };
  14173. /**
  14174. * Set the value of an uniform to a vec3
  14175. * @param uniform defines the webGL uniform location where to store the value
  14176. * @param x defines the 1st component of the value
  14177. * @param y defines the 2nd component of the value
  14178. * @param z defines the 3rd component of the value
  14179. */
  14180. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14181. if (!uniform)
  14182. return;
  14183. this._gl.uniform3f(uniform, x, y, z);
  14184. };
  14185. /**
  14186. * Set the value of an uniform to a boolean
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param bool defines the boolean to store
  14189. */
  14190. Engine.prototype.setBool = function (uniform, bool) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniform1i(uniform, bool);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to a vec4
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param x defines the 1st component of the value
  14199. * @param y defines the 2nd component of the value
  14200. * @param z defines the 3rd component of the value
  14201. * @param w defines the 4th component of the value
  14202. */
  14203. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14204. if (!uniform)
  14205. return;
  14206. this._gl.uniform4f(uniform, x, y, z, w);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to a Color3
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param color3 defines the color to store
  14212. */
  14213. Engine.prototype.setColor3 = function (uniform, color3) {
  14214. if (!uniform)
  14215. return;
  14216. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to a Color3 and an alpha value
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param color3 defines the color to store
  14222. * @param alpha defines the alpha component to store
  14223. */
  14224. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14225. if (!uniform)
  14226. return;
  14227. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14228. };
  14229. /**
  14230. * Sets a Color4 on a uniform variable
  14231. * @param uniform defines the uniform location
  14232. * @param color4 defines the value to be set
  14233. */
  14234. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14235. if (!uniform)
  14236. return;
  14237. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14238. };
  14239. // States
  14240. /**
  14241. * Set various states to the webGL context
  14242. * @param culling defines backface culling state
  14243. * @param zOffset defines the value to apply to zOffset (0 by default)
  14244. * @param force defines if states must be applied even if cache is up to date
  14245. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14246. */
  14247. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14248. if (zOffset === void 0) { zOffset = 0; }
  14249. if (reverseSide === void 0) { reverseSide = false; }
  14250. // Culling
  14251. if (this._depthCullingState.cull !== culling || force) {
  14252. this._depthCullingState.cull = culling;
  14253. }
  14254. // Cull face
  14255. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14256. if (this._depthCullingState.cullFace !== cullFace || force) {
  14257. this._depthCullingState.cullFace = cullFace;
  14258. }
  14259. // Z offset
  14260. this.setZOffset(zOffset);
  14261. // Front face
  14262. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14263. if (this._depthCullingState.frontFace !== frontFace || force) {
  14264. this._depthCullingState.frontFace = frontFace;
  14265. }
  14266. };
  14267. /**
  14268. * Set the z offset to apply to current rendering
  14269. * @param value defines the offset to apply
  14270. */
  14271. Engine.prototype.setZOffset = function (value) {
  14272. this._depthCullingState.zOffset = value;
  14273. };
  14274. /**
  14275. * Gets the current value of the zOffset
  14276. * @returns the current zOffset state
  14277. */
  14278. Engine.prototype.getZOffset = function () {
  14279. return this._depthCullingState.zOffset;
  14280. };
  14281. /**
  14282. * Enable or disable depth buffering
  14283. * @param enable defines the state to set
  14284. */
  14285. Engine.prototype.setDepthBuffer = function (enable) {
  14286. this._depthCullingState.depthTest = enable;
  14287. };
  14288. /**
  14289. * Gets a boolean indicating if depth writing is enabled
  14290. * @returns the current depth writing state
  14291. */
  14292. Engine.prototype.getDepthWrite = function () {
  14293. return this._depthCullingState.depthMask;
  14294. };
  14295. /**
  14296. * Enable or disable depth writing
  14297. * @param enable defines the state to set
  14298. */
  14299. Engine.prototype.setDepthWrite = function (enable) {
  14300. this._depthCullingState.depthMask = enable;
  14301. };
  14302. /**
  14303. * Enable or disable color writing
  14304. * @param enable defines the state to set
  14305. */
  14306. Engine.prototype.setColorWrite = function (enable) {
  14307. this._gl.colorMask(enable, enable, enable, enable);
  14308. this._colorWrite = enable;
  14309. };
  14310. /**
  14311. * Gets a boolean indicating if color writing is enabled
  14312. * @returns the current color writing state
  14313. */
  14314. Engine.prototype.getColorWrite = function () {
  14315. return this._colorWrite;
  14316. };
  14317. /**
  14318. * Sets alpha constants used by some alpha blending modes
  14319. * @param r defines the red component
  14320. * @param g defines the green component
  14321. * @param b defines the blue component
  14322. * @param a defines the alpha component
  14323. */
  14324. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14325. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14326. };
  14327. /**
  14328. * Sets the current alpha mode
  14329. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14330. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14331. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14332. */
  14333. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14334. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14335. if (this._alphaMode === mode) {
  14336. return;
  14337. }
  14338. switch (mode) {
  14339. case Engine.ALPHA_DISABLE:
  14340. this._alphaState.alphaBlend = false;
  14341. break;
  14342. case Engine.ALPHA_PREMULTIPLIED:
  14343. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14344. this._alphaState.alphaBlend = true;
  14345. break;
  14346. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14347. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14348. this._alphaState.alphaBlend = true;
  14349. break;
  14350. case Engine.ALPHA_COMBINE:
  14351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14352. this._alphaState.alphaBlend = true;
  14353. break;
  14354. case Engine.ALPHA_ONEONE:
  14355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14356. this._alphaState.alphaBlend = true;
  14357. break;
  14358. case Engine.ALPHA_ADD:
  14359. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14360. this._alphaState.alphaBlend = true;
  14361. break;
  14362. case Engine.ALPHA_SUBTRACT:
  14363. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14364. this._alphaState.alphaBlend = true;
  14365. break;
  14366. case Engine.ALPHA_MULTIPLY:
  14367. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14368. this._alphaState.alphaBlend = true;
  14369. break;
  14370. case Engine.ALPHA_MAXIMIZED:
  14371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14372. this._alphaState.alphaBlend = true;
  14373. break;
  14374. case Engine.ALPHA_INTERPOLATE:
  14375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14376. this._alphaState.alphaBlend = true;
  14377. break;
  14378. case Engine.ALPHA_SCREENMODE:
  14379. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14380. this._alphaState.alphaBlend = true;
  14381. break;
  14382. }
  14383. if (!noDepthWriteChange) {
  14384. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14385. }
  14386. this._alphaMode = mode;
  14387. };
  14388. /**
  14389. * Gets the current alpha mode
  14390. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14391. * @returns the current alpha mode
  14392. */
  14393. Engine.prototype.getAlphaMode = function () {
  14394. return this._alphaMode;
  14395. };
  14396. // Textures
  14397. /**
  14398. * Force the entire cache to be cleared
  14399. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14400. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14401. */
  14402. Engine.prototype.wipeCaches = function (bruteForce) {
  14403. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14404. return;
  14405. }
  14406. this._currentEffect = null;
  14407. if (bruteForce) {
  14408. this.resetTextureCache();
  14409. this._currentProgram = null;
  14410. this._stencilState.reset();
  14411. this._depthCullingState.reset();
  14412. this.setDepthFunctionToLessOrEqual();
  14413. this._alphaState.reset();
  14414. }
  14415. this._resetVertexBufferBinding();
  14416. this._cachedIndexBuffer = null;
  14417. this._cachedEffectForVertexBuffers = null;
  14418. this._unbindVertexArrayObject();
  14419. this.bindIndexBuffer(null);
  14420. };
  14421. /**
  14422. * Set the compressed texture format to use, based on the formats you have, and the formats
  14423. * supported by the hardware / browser.
  14424. *
  14425. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14426. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14427. * to API arguments needed to compressed textures. This puts the burden on the container
  14428. * generator to house the arcane code for determining these for current & future formats.
  14429. *
  14430. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14431. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14432. *
  14433. * Note: The result of this call is not taken into account when a texture is base64.
  14434. *
  14435. * @param formatsAvailable defines the list of those format families you have created
  14436. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14437. *
  14438. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14439. * @returns The extension selected.
  14440. */
  14441. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14442. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14443. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14444. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14445. return this._textureFormatInUse = this._texturesSupported[i];
  14446. }
  14447. }
  14448. }
  14449. // actively set format to nothing, to allow this to be called more than once
  14450. // and possibly fail the 2nd time
  14451. this._textureFormatInUse = null;
  14452. return null;
  14453. };
  14454. /** @hidden */
  14455. Engine.prototype._createTexture = function () {
  14456. var texture = this._gl.createTexture();
  14457. if (!texture) {
  14458. throw new Error("Unable to create texture");
  14459. }
  14460. return texture;
  14461. };
  14462. /**
  14463. * Usually called from BABYLON.Texture.ts.
  14464. * Passed information to create a WebGLTexture
  14465. * @param urlArg defines a value which contains one of the following:
  14466. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14467. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14468. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14469. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14470. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14471. * @param scene needed for loading to the correct scene
  14472. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14473. * @param onLoad optional callback to be called upon successful completion
  14474. * @param onError optional callback to be called upon failure
  14475. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14476. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14477. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14478. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14479. */
  14480. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14481. var _this = this;
  14482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14483. if (onLoad === void 0) { onLoad = null; }
  14484. if (onError === void 0) { onError = null; }
  14485. if (buffer === void 0) { buffer = null; }
  14486. if (fallback === void 0) { fallback = null; }
  14487. if (format === void 0) { format = null; }
  14488. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14489. var fromData = url.substr(0, 5) === "data:";
  14490. var fromBlob = url.substr(0, 5) === "blob:";
  14491. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14492. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14493. // establish the file extension, if possible
  14494. var lastDot = url.lastIndexOf('.');
  14495. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14496. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14497. var isTGA = (extension.indexOf(".tga") === 0);
  14498. // determine if a ktx file should be substituted
  14499. var isKTX = false;
  14500. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14501. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14502. isKTX = true;
  14503. }
  14504. if (scene) {
  14505. scene._addPendingData(texture);
  14506. }
  14507. texture.url = url;
  14508. texture.generateMipMaps = !noMipmap;
  14509. texture.samplingMode = samplingMode;
  14510. texture.invertY = invertY;
  14511. if (!this._doNotHandleContextLost) {
  14512. // Keep a link to the buffer only if we plan to handle context lost
  14513. texture._buffer = buffer;
  14514. }
  14515. var onLoadObserver = null;
  14516. if (onLoad && !fallback) {
  14517. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14518. }
  14519. if (!fallback)
  14520. this._internalTexturesCache.push(texture);
  14521. var onerror = function (message, exception) {
  14522. if (scene) {
  14523. scene._removePendingData(texture);
  14524. }
  14525. if (onLoadObserver) {
  14526. texture.onLoadedObservable.remove(onLoadObserver);
  14527. }
  14528. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14529. if (isKTX) {
  14530. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14531. }
  14532. else if (BABYLON.Tools.UseFallbackTexture) {
  14533. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14534. }
  14535. if (onError) {
  14536. onError(message || "Unknown error", exception);
  14537. }
  14538. };
  14539. var callback = null;
  14540. // processing for non-image formats
  14541. if (isKTX || isTGA || isDDS) {
  14542. if (isKTX) {
  14543. callback = function (data) {
  14544. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14545. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14546. ktx.uploadLevels(_this._gl, !noMipmap);
  14547. return false;
  14548. }, samplingMode);
  14549. };
  14550. }
  14551. else if (isTGA) {
  14552. callback = function (arrayBuffer) {
  14553. var data = new Uint8Array(arrayBuffer);
  14554. var header = BABYLON.TGATools.GetTGAHeader(data);
  14555. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14556. BABYLON.TGATools.UploadContent(_this._gl, data);
  14557. return false;
  14558. }, samplingMode);
  14559. };
  14560. }
  14561. else if (isDDS) {
  14562. callback = function (data) {
  14563. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14564. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14565. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14566. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14567. return false;
  14568. }, samplingMode);
  14569. };
  14570. }
  14571. if (!buffer) {
  14572. this._loadFile(url, function (data) {
  14573. if (callback) {
  14574. callback(data);
  14575. }
  14576. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14577. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14578. });
  14579. }
  14580. else {
  14581. if (callback) {
  14582. callback(buffer);
  14583. }
  14584. }
  14585. // image format processing
  14586. }
  14587. else {
  14588. var onload = function (img) {
  14589. if (fromBlob && !_this._doNotHandleContextLost) {
  14590. // We need to store the image if we need to rebuild the texture
  14591. // in case of a webgl context lost
  14592. texture._buffer = img;
  14593. }
  14594. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14595. var gl = _this._gl;
  14596. var isPot = (img.width === potWidth && img.height === potHeight);
  14597. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14598. if (isPot) {
  14599. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14600. return false;
  14601. }
  14602. // Using shaders to rescale because canvas.drawImage is lossy
  14603. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14604. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14605. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14610. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14611. _this._releaseTexture(source);
  14612. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14613. continuationCallback();
  14614. });
  14615. return true;
  14616. }, samplingMode);
  14617. };
  14618. if (!fromData || isBase64)
  14619. if (buffer instanceof HTMLImageElement) {
  14620. onload(buffer);
  14621. }
  14622. else {
  14623. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14624. }
  14625. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14626. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14627. else
  14628. onload(buffer);
  14629. }
  14630. return texture;
  14631. };
  14632. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14633. var _this = this;
  14634. var rtt = this.createRenderTargetTexture({
  14635. width: destination.width,
  14636. height: destination.height,
  14637. }, {
  14638. generateMipMaps: false,
  14639. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14640. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14641. generateDepthBuffer: false,
  14642. generateStencilBuffer: false
  14643. });
  14644. if (!this._rescalePostProcess) {
  14645. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14646. }
  14647. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14648. _this._rescalePostProcess.onApply = function (effect) {
  14649. effect._bindTexture("textureSampler", source);
  14650. };
  14651. var hostingScene = scene;
  14652. if (!hostingScene) {
  14653. hostingScene = _this.scenes[_this.scenes.length - 1];
  14654. }
  14655. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14656. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14657. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14658. _this.unBindFramebuffer(rtt);
  14659. _this._releaseTexture(rtt);
  14660. if (onComplete) {
  14661. onComplete();
  14662. }
  14663. });
  14664. };
  14665. /**
  14666. * Update a raw texture
  14667. * @param texture defines the texture to update
  14668. * @param data defines the data to store in the texture
  14669. * @param format defines the format of the data
  14670. * @param invertY defines if data must be stored with Y axis inverted
  14671. * @param compression defines the compression used (null by default)
  14672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14673. */
  14674. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14675. if (compression === void 0) { compression = null; }
  14676. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14677. if (!texture) {
  14678. return;
  14679. }
  14680. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14681. var internalFormat = this._getInternalFormat(format);
  14682. var textureType = this._getWebGLTextureType(type);
  14683. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14684. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14685. if (!this._doNotHandleContextLost) {
  14686. texture._bufferView = data;
  14687. texture.format = format;
  14688. texture.type = type;
  14689. texture.invertY = invertY;
  14690. texture._compression = compression;
  14691. }
  14692. if (texture.width % 4 !== 0) {
  14693. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14694. }
  14695. if (compression && data) {
  14696. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14697. }
  14698. else {
  14699. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14700. }
  14701. if (texture.generateMipMaps) {
  14702. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14703. }
  14704. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14705. // this.resetTextureCache();
  14706. texture.isReady = true;
  14707. };
  14708. /**
  14709. * Creates a raw texture
  14710. * @param data defines the data to store in the texture
  14711. * @param width defines the width of the texture
  14712. * @param height defines the height of the texture
  14713. * @param format defines the format of the data
  14714. * @param generateMipMaps defines if the engine should generate the mip levels
  14715. * @param invertY defines if data must be stored with Y axis inverted
  14716. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14717. * @param compression defines the compression used (null by default)
  14718. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14719. * @returns the raw texture inside an InternalTexture
  14720. */
  14721. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14722. if (compression === void 0) { compression = null; }
  14723. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14724. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14725. texture.baseWidth = width;
  14726. texture.baseHeight = height;
  14727. texture.width = width;
  14728. texture.height = height;
  14729. texture.format = format;
  14730. texture.generateMipMaps = generateMipMaps;
  14731. texture.samplingMode = samplingMode;
  14732. texture.invertY = invertY;
  14733. texture._compression = compression;
  14734. texture.type = type;
  14735. if (!this._doNotHandleContextLost) {
  14736. texture._bufferView = data;
  14737. }
  14738. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14739. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14740. // Filters
  14741. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14742. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14743. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14744. if (generateMipMaps) {
  14745. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14746. }
  14747. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14748. this._internalTexturesCache.push(texture);
  14749. return texture;
  14750. };
  14751. /**
  14752. * Creates a dynamic texture
  14753. * @param width defines the width of the texture
  14754. * @param height defines the height of the texture
  14755. * @param generateMipMaps defines if the engine should generate the mip levels
  14756. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14757. * @returns the dynamic texture inside an InternalTexture
  14758. */
  14759. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14760. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14761. texture.baseWidth = width;
  14762. texture.baseHeight = height;
  14763. if (generateMipMaps) {
  14764. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14765. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14766. }
  14767. // this.resetTextureCache();
  14768. texture.width = width;
  14769. texture.height = height;
  14770. texture.isReady = false;
  14771. texture.generateMipMaps = generateMipMaps;
  14772. texture.samplingMode = samplingMode;
  14773. this.updateTextureSamplingMode(samplingMode, texture);
  14774. this._internalTexturesCache.push(texture);
  14775. return texture;
  14776. };
  14777. /**
  14778. * Update the sampling mode of a given texture
  14779. * @param samplingMode defines the required sampling mode
  14780. * @param texture defines the texture to update
  14781. */
  14782. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14783. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14784. if (texture.isCube) {
  14785. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14786. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14787. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14788. }
  14789. else if (texture.is3D) {
  14790. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14791. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14792. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14793. }
  14794. else {
  14795. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14796. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14798. }
  14799. texture.samplingMode = samplingMode;
  14800. };
  14801. /**
  14802. * Update the content of a dynamic texture
  14803. * @param texture defines the texture to update
  14804. * @param canvas defines the canvas containing the source
  14805. * @param invertY defines if data must be stored with Y axis inverted
  14806. * @param premulAlpha defines if alpha is stored as premultiplied
  14807. * @param format defines the format of the data
  14808. */
  14809. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14810. if (premulAlpha === void 0) { premulAlpha = false; }
  14811. if (!texture) {
  14812. return;
  14813. }
  14814. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14815. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14816. if (premulAlpha) {
  14817. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14818. }
  14819. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14821. if (texture.generateMipMaps) {
  14822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14823. }
  14824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14825. if (premulAlpha) {
  14826. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14827. }
  14828. texture.isReady = true;
  14829. };
  14830. /**
  14831. * Update a video texture
  14832. * @param texture defines the texture to update
  14833. * @param video defines the video element to use
  14834. * @param invertY defines if data must be stored with Y axis inverted
  14835. */
  14836. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14837. if (!texture || texture._isDisabled) {
  14838. return;
  14839. }
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14841. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14842. try {
  14843. // Testing video texture support
  14844. if (this._videoTextureSupported === undefined) {
  14845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14846. if (this._gl.getError() !== 0) {
  14847. this._videoTextureSupported = false;
  14848. }
  14849. else {
  14850. this._videoTextureSupported = true;
  14851. }
  14852. }
  14853. // Copy video through the current working canvas if video texture is not supported
  14854. if (!this._videoTextureSupported) {
  14855. if (!texture._workingCanvas) {
  14856. texture._workingCanvas = document.createElement("canvas");
  14857. var context = texture._workingCanvas.getContext("2d");
  14858. if (!context) {
  14859. throw new Error("Unable to get 2d context");
  14860. }
  14861. texture._workingContext = context;
  14862. texture._workingCanvas.width = texture.width;
  14863. texture._workingCanvas.height = texture.height;
  14864. }
  14865. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14866. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14867. }
  14868. else {
  14869. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14870. }
  14871. if (texture.generateMipMaps) {
  14872. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14875. // this.resetTextureCache();
  14876. texture.isReady = true;
  14877. }
  14878. catch (ex) {
  14879. // Something unexpected
  14880. // Let's disable the texture
  14881. texture._isDisabled = true;
  14882. }
  14883. };
  14884. /**
  14885. * Updates a depth texture Comparison Mode and Function.
  14886. * If the comparison Function is equal to 0, the mode will be set to none.
  14887. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14888. * @param texture The texture to set the comparison function for
  14889. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14890. */
  14891. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14892. if (this.webGLVersion === 1) {
  14893. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14894. return;
  14895. }
  14896. var gl = this._gl;
  14897. if (texture.isCube) {
  14898. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14899. if (comparisonFunction === 0) {
  14900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14902. }
  14903. else {
  14904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14906. }
  14907. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14908. }
  14909. else {
  14910. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14911. if (comparisonFunction === 0) {
  14912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14914. }
  14915. else {
  14916. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14917. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14918. }
  14919. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14920. }
  14921. texture._comparisonFunction = comparisonFunction;
  14922. };
  14923. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14924. var width = size.width || size;
  14925. var height = size.height || size;
  14926. internalTexture.baseWidth = width;
  14927. internalTexture.baseHeight = height;
  14928. internalTexture.width = width;
  14929. internalTexture.height = height;
  14930. internalTexture.isReady = true;
  14931. internalTexture.samples = 1;
  14932. internalTexture.generateMipMaps = false;
  14933. internalTexture._generateDepthBuffer = true;
  14934. internalTexture._generateStencilBuffer = generateStencil;
  14935. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14936. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14937. internalTexture._comparisonFunction = comparisonFunction;
  14938. var gl = this._gl;
  14939. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14940. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14941. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14942. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14943. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14944. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14945. if (comparisonFunction === 0) {
  14946. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14947. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14948. }
  14949. else {
  14950. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14951. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14952. }
  14953. };
  14954. /**
  14955. * Creates a depth stencil texture.
  14956. * This is only available in WebGL 2 or with the depth texture extension available.
  14957. * @param size The size of face edge in the texture.
  14958. * @param options The options defining the texture.
  14959. * @returns The texture
  14960. */
  14961. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14962. if (options.isCube) {
  14963. var width = size.width || size;
  14964. return this._createDepthStencilCubeTexture(width, options);
  14965. }
  14966. else {
  14967. return this._createDepthStencilTexture(size, options);
  14968. }
  14969. };
  14970. /**
  14971. * Creates a depth stencil texture.
  14972. * This is only available in WebGL 2 or with the depth texture extension available.
  14973. * @param size The size of face edge in the texture.
  14974. * @param options The options defining the texture.
  14975. * @returns The texture
  14976. */
  14977. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14978. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14979. if (!this._caps.depthTextureExtension) {
  14980. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14981. return internalTexture;
  14982. }
  14983. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14984. var gl = this._gl;
  14985. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14986. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14987. if (this.webGLVersion > 1) {
  14988. if (internalOptions.generateStencil) {
  14989. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14990. }
  14991. else {
  14992. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14993. }
  14994. }
  14995. else {
  14996. if (internalOptions.generateStencil) {
  14997. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14998. }
  14999. else {
  15000. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15001. }
  15002. }
  15003. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15004. return internalTexture;
  15005. };
  15006. /**
  15007. * Creates a depth stencil cube texture.
  15008. * This is only available in WebGL 2.
  15009. * @param size The size of face edge in the cube texture.
  15010. * @param options The options defining the cube texture.
  15011. * @returns The cube texture
  15012. */
  15013. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15014. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15015. internalTexture.isCube = true;
  15016. if (this.webGLVersion === 1) {
  15017. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15018. return internalTexture;
  15019. }
  15020. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15021. var gl = this._gl;
  15022. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15023. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15024. // Create the depth/stencil buffer
  15025. for (var face = 0; face < 6; face++) {
  15026. if (internalOptions.generateStencil) {
  15027. 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);
  15028. }
  15029. else {
  15030. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15031. }
  15032. }
  15033. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15034. return internalTexture;
  15035. };
  15036. /**
  15037. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15038. * @param renderTarget The render target to set the frame buffer for
  15039. */
  15040. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15041. // Create the framebuffer
  15042. var internalTexture = renderTarget.getInternalTexture();
  15043. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15044. return;
  15045. }
  15046. var gl = this._gl;
  15047. var depthStencilTexture = renderTarget.depthStencilTexture;
  15048. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15049. if (depthStencilTexture.isCube) {
  15050. if (depthStencilTexture._generateStencilBuffer) {
  15051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15052. }
  15053. else {
  15054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15055. }
  15056. }
  15057. else {
  15058. if (depthStencilTexture._generateStencilBuffer) {
  15059. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15060. }
  15061. else {
  15062. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15063. }
  15064. }
  15065. this.bindUnboundFramebuffer(null);
  15066. };
  15067. /**
  15068. * Creates a new render target texture
  15069. * @param size defines the size of the texture
  15070. * @param options defines the options used to create the texture
  15071. * @returns a new render target texture stored in an InternalTexture
  15072. */
  15073. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15074. var fullOptions = new RenderTargetCreationOptions();
  15075. if (options !== undefined && typeof options === "object") {
  15076. fullOptions.generateMipMaps = options.generateMipMaps;
  15077. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15078. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15079. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15080. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15081. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15082. }
  15083. else {
  15084. fullOptions.generateMipMaps = options;
  15085. fullOptions.generateDepthBuffer = true;
  15086. fullOptions.generateStencilBuffer = false;
  15087. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15088. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15089. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15090. }
  15091. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15092. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15093. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15094. }
  15095. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15096. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15097. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15098. }
  15099. var gl = this._gl;
  15100. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15101. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15102. var width = size.width || size;
  15103. var height = size.height || size;
  15104. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15105. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15106. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15107. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15108. }
  15109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15113. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15114. // Create the framebuffer
  15115. var framebuffer = gl.createFramebuffer();
  15116. this.bindUnboundFramebuffer(framebuffer);
  15117. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15118. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15119. if (fullOptions.generateMipMaps) {
  15120. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15121. }
  15122. // Unbind
  15123. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15124. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15125. this.bindUnboundFramebuffer(null);
  15126. texture._framebuffer = framebuffer;
  15127. texture.baseWidth = width;
  15128. texture.baseHeight = height;
  15129. texture.width = width;
  15130. texture.height = height;
  15131. texture.isReady = true;
  15132. texture.samples = 1;
  15133. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15134. texture.samplingMode = fullOptions.samplingMode;
  15135. texture.type = fullOptions.type;
  15136. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15137. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15138. // this.resetTextureCache();
  15139. this._internalTexturesCache.push(texture);
  15140. return texture;
  15141. };
  15142. /**
  15143. * Create a multi render target texture
  15144. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15145. * @param size defines the size of the texture
  15146. * @param options defines the creation options
  15147. * @returns the cube texture as an InternalTexture
  15148. */
  15149. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15150. var generateMipMaps = false;
  15151. var generateDepthBuffer = true;
  15152. var generateStencilBuffer = false;
  15153. var generateDepthTexture = false;
  15154. var textureCount = 1;
  15155. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15156. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15157. var types = new Array();
  15158. var samplingModes = new Array();
  15159. if (options !== undefined) {
  15160. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15161. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15162. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15163. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15164. textureCount = options.textureCount || 1;
  15165. if (options.types) {
  15166. types = options.types;
  15167. }
  15168. if (options.samplingModes) {
  15169. samplingModes = options.samplingModes;
  15170. }
  15171. }
  15172. var gl = this._gl;
  15173. // Create the framebuffer
  15174. var framebuffer = gl.createFramebuffer();
  15175. this.bindUnboundFramebuffer(framebuffer);
  15176. var width = size.width || size;
  15177. var height = size.height || size;
  15178. var textures = [];
  15179. var attachments = [];
  15180. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15181. for (var i = 0; i < textureCount; i++) {
  15182. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15183. var type = types[i] || defaultType;
  15184. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15185. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15186. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15187. }
  15188. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15189. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15190. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15191. }
  15192. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15193. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15194. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15195. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15196. }
  15197. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15198. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15199. textures.push(texture);
  15200. attachments.push(attachment);
  15201. gl.activeTexture(gl["TEXTURE" + i]);
  15202. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15207. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15208. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15209. if (generateMipMaps) {
  15210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15211. }
  15212. // Unbind
  15213. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15214. texture._framebuffer = framebuffer;
  15215. texture._depthStencilBuffer = depthStencilBuffer;
  15216. texture.baseWidth = width;
  15217. texture.baseHeight = height;
  15218. texture.width = width;
  15219. texture.height = height;
  15220. texture.isReady = true;
  15221. texture.samples = 1;
  15222. texture.generateMipMaps = generateMipMaps;
  15223. texture.samplingMode = samplingMode;
  15224. texture.type = type;
  15225. texture._generateDepthBuffer = generateDepthBuffer;
  15226. texture._generateStencilBuffer = generateStencilBuffer;
  15227. texture._attachments = attachments;
  15228. this._internalTexturesCache.push(texture);
  15229. }
  15230. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15231. // Depth texture
  15232. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15233. gl.activeTexture(gl.TEXTURE0);
  15234. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15239. 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);
  15240. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15241. depthTexture._framebuffer = framebuffer;
  15242. depthTexture.baseWidth = width;
  15243. depthTexture.baseHeight = height;
  15244. depthTexture.width = width;
  15245. depthTexture.height = height;
  15246. depthTexture.isReady = true;
  15247. depthTexture.samples = 1;
  15248. depthTexture.generateMipMaps = generateMipMaps;
  15249. depthTexture.samplingMode = gl.NEAREST;
  15250. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15251. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15252. textures.push(depthTexture);
  15253. this._internalTexturesCache.push(depthTexture);
  15254. }
  15255. gl.drawBuffers(attachments);
  15256. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15257. this.bindUnboundFramebuffer(null);
  15258. this.resetTextureCache();
  15259. return textures;
  15260. };
  15261. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15262. if (samples === void 0) { samples = 1; }
  15263. var depthStencilBuffer = null;
  15264. var gl = this._gl;
  15265. // Create the depth/stencil buffer
  15266. if (generateStencilBuffer) {
  15267. depthStencilBuffer = gl.createRenderbuffer();
  15268. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15269. if (samples > 1) {
  15270. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15271. }
  15272. else {
  15273. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15274. }
  15275. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15276. }
  15277. else if (generateDepthBuffer) {
  15278. depthStencilBuffer = gl.createRenderbuffer();
  15279. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15280. if (samples > 1) {
  15281. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15282. }
  15283. else {
  15284. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15285. }
  15286. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15287. }
  15288. return depthStencilBuffer;
  15289. };
  15290. /**
  15291. * Updates the sample count of a render target texture
  15292. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15293. * @param texture defines the texture to update
  15294. * @param samples defines the sample count to set
  15295. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15296. */
  15297. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15298. if (this.webGLVersion < 2 || !texture) {
  15299. return 1;
  15300. }
  15301. if (texture.samples === samples) {
  15302. return samples;
  15303. }
  15304. var gl = this._gl;
  15305. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15306. // Dispose previous render buffers
  15307. if (texture._depthStencilBuffer) {
  15308. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15309. texture._depthStencilBuffer = null;
  15310. }
  15311. if (texture._MSAAFramebuffer) {
  15312. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15313. texture._MSAAFramebuffer = null;
  15314. }
  15315. if (texture._MSAARenderBuffer) {
  15316. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15317. texture._MSAARenderBuffer = null;
  15318. }
  15319. if (samples > 1) {
  15320. var framebuffer = gl.createFramebuffer();
  15321. if (!framebuffer) {
  15322. throw new Error("Unable to create multi sampled framebuffer");
  15323. }
  15324. texture._MSAAFramebuffer = framebuffer;
  15325. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15326. var colorRenderbuffer = gl.createRenderbuffer();
  15327. if (!colorRenderbuffer) {
  15328. throw new Error("Unable to create multi sampled framebuffer");
  15329. }
  15330. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15331. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15332. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15333. texture._MSAARenderBuffer = colorRenderbuffer;
  15334. }
  15335. else {
  15336. this.bindUnboundFramebuffer(texture._framebuffer);
  15337. }
  15338. texture.samples = samples;
  15339. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15340. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15341. this.bindUnboundFramebuffer(null);
  15342. return samples;
  15343. };
  15344. /**
  15345. * Update the sample count for a given multiple render target texture
  15346. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15347. * @param textures defines the textures to update
  15348. * @param samples defines the sample count to set
  15349. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15350. */
  15351. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15352. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15353. return 1;
  15354. }
  15355. if (textures[0].samples === samples) {
  15356. return samples;
  15357. }
  15358. var gl = this._gl;
  15359. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15360. // Dispose previous render buffers
  15361. if (textures[0]._depthStencilBuffer) {
  15362. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15363. textures[0]._depthStencilBuffer = null;
  15364. }
  15365. if (textures[0]._MSAAFramebuffer) {
  15366. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15367. textures[0]._MSAAFramebuffer = null;
  15368. }
  15369. for (var i = 0; i < textures.length; i++) {
  15370. if (textures[i]._MSAARenderBuffer) {
  15371. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15372. textures[i]._MSAARenderBuffer = null;
  15373. }
  15374. }
  15375. if (samples > 1) {
  15376. var framebuffer = gl.createFramebuffer();
  15377. if (!framebuffer) {
  15378. throw new Error("Unable to create multi sampled framebuffer");
  15379. }
  15380. this.bindUnboundFramebuffer(framebuffer);
  15381. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15382. var attachments = [];
  15383. for (var i = 0; i < textures.length; i++) {
  15384. var texture = textures[i];
  15385. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15386. var colorRenderbuffer = gl.createRenderbuffer();
  15387. if (!colorRenderbuffer) {
  15388. throw new Error("Unable to create multi sampled framebuffer");
  15389. }
  15390. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15391. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15392. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15393. texture._MSAAFramebuffer = framebuffer;
  15394. texture._MSAARenderBuffer = colorRenderbuffer;
  15395. texture.samples = samples;
  15396. texture._depthStencilBuffer = depthStencilBuffer;
  15397. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15398. attachments.push(attachment);
  15399. }
  15400. gl.drawBuffers(attachments);
  15401. }
  15402. else {
  15403. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15404. }
  15405. this.bindUnboundFramebuffer(null);
  15406. return samples;
  15407. };
  15408. /** @hidden */
  15409. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15410. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15411. };
  15412. /** @hidden */
  15413. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15414. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15415. };
  15416. /**
  15417. * Creates a new render target cube texture
  15418. * @param size defines the size of the texture
  15419. * @param options defines the options used to create the texture
  15420. * @returns a new render target cube texture stored in an InternalTexture
  15421. */
  15422. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15423. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15424. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15425. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15426. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15427. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15428. }
  15429. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15430. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15431. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15432. }
  15433. var gl = this._gl;
  15434. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15435. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15436. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15437. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15438. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15439. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15440. }
  15441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15445. for (var face = 0; face < 6; face++) {
  15446. 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);
  15447. }
  15448. // Create the framebuffer
  15449. var framebuffer = gl.createFramebuffer();
  15450. this.bindUnboundFramebuffer(framebuffer);
  15451. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15452. // MipMaps
  15453. if (fullOptions.generateMipMaps) {
  15454. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15455. }
  15456. // Unbind
  15457. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15458. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15459. this.bindUnboundFramebuffer(null);
  15460. texture._framebuffer = framebuffer;
  15461. texture.width = size;
  15462. texture.height = size;
  15463. texture.isReady = true;
  15464. texture.isCube = true;
  15465. texture.samples = 1;
  15466. texture.generateMipMaps = fullOptions.generateMipMaps;
  15467. texture.samplingMode = fullOptions.samplingMode;
  15468. texture.type = fullOptions.type;
  15469. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15470. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15471. this._internalTexturesCache.push(texture);
  15472. return texture;
  15473. };
  15474. /**
  15475. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15476. * @param rootUrl defines the url where the file to load is located
  15477. * @param scene defines the current scene
  15478. * @param scale defines scale to apply to the mip map selection
  15479. * @param offset defines offset to apply to the mip map selection
  15480. * @param onLoad defines an optional callback raised when the texture is loaded
  15481. * @param onError defines an optional callback raised if there is an issue to load the texture
  15482. * @param format defines the format of the data
  15483. * @param forcedExtension defines the extension to use to pick the right loader
  15484. * @returns the cube texture as an InternalTexture
  15485. */
  15486. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15487. var _this = this;
  15488. if (onLoad === void 0) { onLoad = null; }
  15489. if (onError === void 0) { onError = null; }
  15490. if (forcedExtension === void 0) { forcedExtension = null; }
  15491. var callback = function (loadData) {
  15492. if (!loadData) {
  15493. if (onLoad) {
  15494. onLoad(null);
  15495. }
  15496. return;
  15497. }
  15498. var texture = loadData.texture;
  15499. if (loadData.info.sphericalPolynomial) {
  15500. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15501. }
  15502. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15503. texture._lodGenerationScale = scale;
  15504. texture._lodGenerationOffset = offset;
  15505. if (_this._caps.textureLOD) {
  15506. // Do not add extra process if texture lod is supported.
  15507. if (onLoad) {
  15508. onLoad(texture);
  15509. }
  15510. return;
  15511. }
  15512. var mipSlices = 3;
  15513. var gl = _this._gl;
  15514. var width = loadData.width;
  15515. if (!width) {
  15516. return;
  15517. }
  15518. var textures = [];
  15519. for (var i = 0; i < mipSlices; i++) {
  15520. //compute LOD from even spacing in smoothness (matching shader calculation)
  15521. var smoothness = i / (mipSlices - 1);
  15522. var roughness = 1 - smoothness;
  15523. var minLODIndex = offset; // roughness = 0
  15524. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15525. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15526. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15527. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15528. glTextureFromLod.isCube = true;
  15529. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15532. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15533. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15534. if (loadData.isDDS) {
  15535. var info = loadData.info;
  15536. var data = loadData.data;
  15537. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15538. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15539. }
  15540. else {
  15541. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15542. }
  15543. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15544. // Wrap in a base texture for easy binding.
  15545. var lodTexture = new BABYLON.BaseTexture(scene);
  15546. lodTexture.isCube = true;
  15547. lodTexture._texture = glTextureFromLod;
  15548. glTextureFromLod.isReady = true;
  15549. textures.push(lodTexture);
  15550. }
  15551. texture._lodTextureHigh = textures[2];
  15552. texture._lodTextureMid = textures[1];
  15553. texture._lodTextureLow = textures[0];
  15554. if (onLoad) {
  15555. onLoad(texture);
  15556. }
  15557. };
  15558. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15559. };
  15560. /**
  15561. * Creates a cube texture
  15562. * @param rootUrl defines the url where the files to load is located
  15563. * @param scene defines the current scene
  15564. * @param files defines the list of files to load (1 per face)
  15565. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15566. * @param onLoad defines an optional callback raised when the texture is loaded
  15567. * @param onError defines an optional callback raised if there is an issue to load the texture
  15568. * @param format defines the format of the data
  15569. * @param forcedExtension defines the extension to use to pick the right loader
  15570. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15571. * @returns the cube texture as an InternalTexture
  15572. */
  15573. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15574. var _this = this;
  15575. if (onLoad === void 0) { onLoad = null; }
  15576. if (onError === void 0) { onError = null; }
  15577. if (forcedExtension === void 0) { forcedExtension = null; }
  15578. if (createPolynomials === void 0) { createPolynomials = false; }
  15579. var gl = this._gl;
  15580. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15581. texture.isCube = true;
  15582. texture.url = rootUrl;
  15583. texture.generateMipMaps = !noMipmap;
  15584. if (!this._doNotHandleContextLost) {
  15585. texture._extension = forcedExtension;
  15586. texture._files = files;
  15587. }
  15588. var isKTX = false;
  15589. var isDDS = false;
  15590. var lastDot = rootUrl.lastIndexOf('.');
  15591. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15592. if (this._textureFormatInUse) {
  15593. extension = this._textureFormatInUse;
  15594. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15595. isKTX = true;
  15596. }
  15597. else {
  15598. isDDS = (extension === ".dds");
  15599. }
  15600. var onerror = function (request, exception) {
  15601. if (onError && request) {
  15602. onError(request.status + " " + request.statusText, exception);
  15603. }
  15604. };
  15605. if (isKTX) {
  15606. this._loadFile(rootUrl, function (data) {
  15607. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15608. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15609. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15610. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15611. ktx.uploadLevels(_this._gl, !noMipmap);
  15612. _this.setCubeMapTextureParams(gl, loadMipmap);
  15613. texture.width = ktx.pixelWidth;
  15614. texture.height = ktx.pixelHeight;
  15615. texture.isReady = true;
  15616. }, undefined, undefined, true, onerror);
  15617. }
  15618. else if (isDDS) {
  15619. if (files && files.length === 6) {
  15620. this._cascadeLoadFiles(scene, function (imgs) {
  15621. var info;
  15622. var loadMipmap = false;
  15623. var width = 0;
  15624. for (var index = 0; index < imgs.length; index++) {
  15625. var data = imgs[index];
  15626. info = BABYLON.DDSTools.GetDDSInfo(data);
  15627. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15630. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15631. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15632. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15633. }
  15634. texture.width = info.width;
  15635. texture.height = info.height;
  15636. texture.type = info.textureType;
  15637. width = info.width;
  15638. }
  15639. _this.setCubeMapTextureParams(gl, loadMipmap);
  15640. texture.isReady = true;
  15641. if (onLoad) {
  15642. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15643. }
  15644. }, files, onError);
  15645. }
  15646. else {
  15647. this._loadFile(rootUrl, function (data) {
  15648. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15649. if (createPolynomials) {
  15650. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15651. }
  15652. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15653. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15654. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15655. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15656. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15657. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15658. }
  15659. _this.setCubeMapTextureParams(gl, loadMipmap);
  15660. texture.width = info.width;
  15661. texture.height = info.height;
  15662. texture.isReady = true;
  15663. texture.type = info.textureType;
  15664. if (onLoad) {
  15665. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15666. }
  15667. }, undefined, undefined, true, onerror);
  15668. }
  15669. }
  15670. else {
  15671. if (!files) {
  15672. throw new Error("Cannot load cubemap because files were not defined");
  15673. }
  15674. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15675. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15676. var height = width;
  15677. _this._prepareWorkingCanvas();
  15678. if (!_this._workingCanvas || !_this._workingContext) {
  15679. return;
  15680. }
  15681. _this._workingCanvas.width = width;
  15682. _this._workingCanvas.height = height;
  15683. var faces = [
  15684. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15685. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15686. ];
  15687. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15688. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15689. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15690. for (var index = 0; index < faces.length; index++) {
  15691. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15692. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15693. }
  15694. if (!noMipmap) {
  15695. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15696. }
  15697. _this.setCubeMapTextureParams(gl, !noMipmap);
  15698. texture.width = width;
  15699. texture.height = height;
  15700. texture.isReady = true;
  15701. if (format) {
  15702. texture.format = format;
  15703. }
  15704. texture.onLoadedObservable.notifyObservers(texture);
  15705. texture.onLoadedObservable.clear();
  15706. if (onLoad) {
  15707. onLoad();
  15708. }
  15709. }, files, onError);
  15710. }
  15711. this._internalTexturesCache.push(texture);
  15712. return texture;
  15713. };
  15714. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15719. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15720. // this.resetTextureCache();
  15721. };
  15722. /**
  15723. * Update a raw cube texture
  15724. * @param texture defines the texture to udpdate
  15725. * @param data defines the data to store
  15726. * @param format defines the data format
  15727. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15728. * @param invertY defines if data must be stored with Y axis inverted
  15729. * @param compression defines the compression used (null by default)
  15730. * @param level defines which level of the texture to update
  15731. */
  15732. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15733. if (compression === void 0) { compression = null; }
  15734. if (level === void 0) { level = 0; }
  15735. texture._bufferViewArray = data;
  15736. texture.format = format;
  15737. texture.type = type;
  15738. texture.invertY = invertY;
  15739. texture._compression = compression;
  15740. var gl = this._gl;
  15741. var textureType = this._getWebGLTextureType(type);
  15742. var internalFormat = this._getInternalFormat(format);
  15743. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15744. var needConversion = false;
  15745. if (internalFormat === gl.RGB) {
  15746. internalFormat = gl.RGBA;
  15747. needConversion = true;
  15748. }
  15749. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15750. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15751. if (texture.width % 4 !== 0) {
  15752. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15753. }
  15754. // Data are known to be in +X +Y +Z -X -Y -Z
  15755. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15756. var faceData = data[faceIndex];
  15757. if (compression) {
  15758. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15759. }
  15760. else {
  15761. if (needConversion) {
  15762. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15763. }
  15764. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15765. }
  15766. }
  15767. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15768. if (isPot && texture.generateMipMaps && level === 0) {
  15769. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15770. }
  15771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15772. // this.resetTextureCache();
  15773. texture.isReady = true;
  15774. };
  15775. /**
  15776. * Creates a new raw cube texture
  15777. * @param data defines the array of data to use to create each face
  15778. * @param size defines the size of the textures
  15779. * @param format defines the format of the data
  15780. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15781. * @param generateMipMaps defines if the engine should generate the mip levels
  15782. * @param invertY defines if data must be stored with Y axis inverted
  15783. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15784. * @param compression defines the compression used (null by default)
  15785. * @returns the cube texture as an InternalTexture
  15786. */
  15787. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15788. if (compression === void 0) { compression = null; }
  15789. var gl = this._gl;
  15790. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15791. texture.isCube = true;
  15792. texture.generateMipMaps = generateMipMaps;
  15793. texture.format = format;
  15794. texture.type = type;
  15795. if (!this._doNotHandleContextLost) {
  15796. texture._bufferViewArray = data;
  15797. }
  15798. var textureType = this._getWebGLTextureType(type);
  15799. var internalFormat = this._getInternalFormat(format);
  15800. if (internalFormat === gl.RGB) {
  15801. internalFormat = gl.RGBA;
  15802. }
  15803. var width = size;
  15804. var height = width;
  15805. texture.width = width;
  15806. texture.height = height;
  15807. // Double check on POT to generate Mips.
  15808. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15809. if (!isPot) {
  15810. generateMipMaps = false;
  15811. }
  15812. // Upload data if needed. The texture won't be ready until then.
  15813. if (data) {
  15814. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15815. }
  15816. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15817. // Filters
  15818. if (data && generateMipMaps) {
  15819. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15820. }
  15821. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15824. }
  15825. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15828. }
  15829. else {
  15830. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15833. }
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15836. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15837. return texture;
  15838. };
  15839. /**
  15840. * Creates a new raw cube texture from a specified url
  15841. * @param url defines the url where the data is located
  15842. * @param scene defines the current scene
  15843. * @param size defines the size of the textures
  15844. * @param format defines the format of the data
  15845. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15846. * @param noMipmap defines if the engine should avoid generating the mip levels
  15847. * @param callback defines a callback used to extract texture data from loaded data
  15848. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15849. * @param onLoad defines a callback called when texture is loaded
  15850. * @param onError defines a callback called if there is an error
  15851. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15852. * @param invertY defines if data must be stored with Y axis inverted
  15853. * @returns the cube texture as an InternalTexture
  15854. */
  15855. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15856. var _this = this;
  15857. if (onLoad === void 0) { onLoad = null; }
  15858. if (onError === void 0) { onError = null; }
  15859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15860. if (invertY === void 0) { invertY = false; }
  15861. var gl = this._gl;
  15862. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15863. scene._addPendingData(texture);
  15864. texture.url = url;
  15865. this._internalTexturesCache.push(texture);
  15866. var onerror = function (request, exception) {
  15867. scene._removePendingData(texture);
  15868. if (onError && request) {
  15869. onError(request.status + " " + request.statusText, exception);
  15870. }
  15871. };
  15872. var internalCallback = function (data) {
  15873. var width = texture.width;
  15874. var faceDataArrays = callback(data);
  15875. if (!faceDataArrays) {
  15876. return;
  15877. }
  15878. if (mipmapGenerator) {
  15879. var textureType = _this._getWebGLTextureType(type);
  15880. var internalFormat = _this._getInternalFormat(format);
  15881. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15882. var needConversion = false;
  15883. if (internalFormat === gl.RGB) {
  15884. internalFormat = gl.RGBA;
  15885. needConversion = true;
  15886. }
  15887. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15888. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15889. var mipData = mipmapGenerator(faceDataArrays);
  15890. for (var level = 0; level < mipData.length; level++) {
  15891. var mipSize = width >> level;
  15892. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15893. var mipFaceData = mipData[level][faceIndex];
  15894. if (needConversion) {
  15895. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15896. }
  15897. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15898. }
  15899. }
  15900. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15901. }
  15902. else {
  15903. texture.generateMipMaps = !noMipmap;
  15904. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15905. }
  15906. texture.isReady = true;
  15907. // this.resetTextureCache();
  15908. scene._removePendingData(texture);
  15909. if (onLoad) {
  15910. onLoad();
  15911. }
  15912. };
  15913. this._loadFile(url, function (data) {
  15914. internalCallback(data);
  15915. }, undefined, scene.database, true, onerror);
  15916. return texture;
  15917. };
  15918. ;
  15919. /**
  15920. * Update a raw 3D texture
  15921. * @param texture defines the texture to update
  15922. * @param data defines the data to store
  15923. * @param format defines the data format
  15924. * @param invertY defines if data must be stored with Y axis inverted
  15925. * @param compression defines the used compression (can be null)
  15926. */
  15927. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15928. if (compression === void 0) { compression = null; }
  15929. var internalFormat = this._getInternalFormat(format);
  15930. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15931. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15932. if (!this._doNotHandleContextLost) {
  15933. texture._bufferView = data;
  15934. texture.format = format;
  15935. texture.invertY = invertY;
  15936. texture._compression = compression;
  15937. }
  15938. if (texture.width % 4 !== 0) {
  15939. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15940. }
  15941. if (compression && data) {
  15942. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15943. }
  15944. else {
  15945. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15946. }
  15947. if (texture.generateMipMaps) {
  15948. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15949. }
  15950. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15951. // this.resetTextureCache();
  15952. texture.isReady = true;
  15953. };
  15954. /**
  15955. * Creates a new raw 3D texture
  15956. * @param data defines the data used to create the texture
  15957. * @param width defines the width of the texture
  15958. * @param height defines the height of the texture
  15959. * @param depth defines the depth of the texture
  15960. * @param format defines the format of the texture
  15961. * @param generateMipMaps defines if the engine must generate mip levels
  15962. * @param invertY defines if data must be stored with Y axis inverted
  15963. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15964. * @param compression defines the compressed used (can be null)
  15965. * @returns a new raw 3D texture (stored in an InternalTexture)
  15966. */
  15967. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15968. if (compression === void 0) { compression = null; }
  15969. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15970. texture.baseWidth = width;
  15971. texture.baseHeight = height;
  15972. texture.baseDepth = depth;
  15973. texture.width = width;
  15974. texture.height = height;
  15975. texture.depth = depth;
  15976. texture.format = format;
  15977. texture.generateMipMaps = generateMipMaps;
  15978. texture.samplingMode = samplingMode;
  15979. texture.is3D = true;
  15980. if (!this._doNotHandleContextLost) {
  15981. texture._bufferView = data;
  15982. }
  15983. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15984. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15985. // Filters
  15986. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15987. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15988. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15989. if (generateMipMaps) {
  15990. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15991. }
  15992. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15993. this._internalTexturesCache.push(texture);
  15994. return texture;
  15995. };
  15996. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15997. var gl = this._gl;
  15998. if (!gl) {
  15999. return;
  16000. }
  16001. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16004. if (!noMipmap && !isCompressed) {
  16005. gl.generateMipmap(gl.TEXTURE_2D);
  16006. }
  16007. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16008. // this.resetTextureCache();
  16009. if (scene) {
  16010. scene._removePendingData(texture);
  16011. }
  16012. texture.onLoadedObservable.notifyObservers(texture);
  16013. texture.onLoadedObservable.clear();
  16014. };
  16015. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16016. var _this = this;
  16017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16018. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16019. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16020. var gl = this._gl;
  16021. if (!gl) {
  16022. return;
  16023. }
  16024. if (!texture._webGLTexture) {
  16025. // this.resetTextureCache();
  16026. if (scene) {
  16027. scene._removePendingData(texture);
  16028. }
  16029. return;
  16030. }
  16031. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16032. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16033. texture.baseWidth = width;
  16034. texture.baseHeight = height;
  16035. texture.width = potWidth;
  16036. texture.height = potHeight;
  16037. texture.isReady = true;
  16038. if (processFunction(potWidth, potHeight, function () {
  16039. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16040. })) {
  16041. // Returning as texture needs extra async steps
  16042. return;
  16043. }
  16044. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16045. };
  16046. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16047. // Create new RGBA data container.
  16048. var rgbaData;
  16049. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16050. rgbaData = new Float32Array(width * height * 4);
  16051. }
  16052. else {
  16053. rgbaData = new Uint32Array(width * height * 4);
  16054. }
  16055. // Convert each pixel.
  16056. for (var x = 0; x < width; x++) {
  16057. for (var y = 0; y < height; y++) {
  16058. var index = (y * width + x) * 3;
  16059. var newIndex = (y * width + x) * 4;
  16060. // Map Old Value to new value.
  16061. rgbaData[newIndex + 0] = rgbData[index + 0];
  16062. rgbaData[newIndex + 1] = rgbData[index + 1];
  16063. rgbaData[newIndex + 2] = rgbData[index + 2];
  16064. // Add fully opaque alpha channel.
  16065. rgbaData[newIndex + 3] = 1;
  16066. }
  16067. }
  16068. return rgbaData;
  16069. };
  16070. /** @hidden */
  16071. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16072. var gl = this._gl;
  16073. if (texture._framebuffer) {
  16074. gl.deleteFramebuffer(texture._framebuffer);
  16075. texture._framebuffer = null;
  16076. }
  16077. if (texture._depthStencilBuffer) {
  16078. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16079. texture._depthStencilBuffer = null;
  16080. }
  16081. if (texture._MSAAFramebuffer) {
  16082. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16083. texture._MSAAFramebuffer = null;
  16084. }
  16085. if (texture._MSAARenderBuffer) {
  16086. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16087. texture._MSAARenderBuffer = null;
  16088. }
  16089. };
  16090. /** @hidden */
  16091. Engine.prototype._releaseTexture = function (texture) {
  16092. var gl = this._gl;
  16093. this._releaseFramebufferObjects(texture);
  16094. gl.deleteTexture(texture._webGLTexture);
  16095. // Unbind channels
  16096. this.unbindAllTextures();
  16097. var index = this._internalTexturesCache.indexOf(texture);
  16098. if (index !== -1) {
  16099. this._internalTexturesCache.splice(index, 1);
  16100. }
  16101. // Integrated fixed lod samplers.
  16102. if (texture._lodTextureHigh) {
  16103. texture._lodTextureHigh.dispose();
  16104. }
  16105. if (texture._lodTextureMid) {
  16106. texture._lodTextureMid.dispose();
  16107. }
  16108. if (texture._lodTextureLow) {
  16109. texture._lodTextureLow.dispose();
  16110. }
  16111. // Set output texture of post process to null if the texture has been released/disposed
  16112. this.scenes.forEach(function (scene) {
  16113. scene.postProcesses.forEach(function (postProcess) {
  16114. if (postProcess._outputTexture == texture) {
  16115. postProcess._outputTexture = null;
  16116. }
  16117. });
  16118. scene.cameras.forEach(function (camera) {
  16119. camera._postProcesses.forEach(function (postProcess) {
  16120. if (postProcess) {
  16121. if (postProcess._outputTexture == texture) {
  16122. postProcess._outputTexture = null;
  16123. }
  16124. }
  16125. });
  16126. });
  16127. });
  16128. };
  16129. Engine.prototype.setProgram = function (program) {
  16130. if (this._currentProgram !== program) {
  16131. this._gl.useProgram(program);
  16132. this._currentProgram = program;
  16133. }
  16134. };
  16135. /**
  16136. * Binds an effect to the webGL context
  16137. * @param effect defines the effect to bind
  16138. */
  16139. Engine.prototype.bindSamplers = function (effect) {
  16140. this.setProgram(effect.getProgram());
  16141. var samplers = effect.getSamplers();
  16142. for (var index = 0; index < samplers.length; index++) {
  16143. var uniform = effect.getUniform(samplers[index]);
  16144. if (uniform) {
  16145. this._boundUniforms[index] = uniform;
  16146. }
  16147. }
  16148. this._currentEffect = null;
  16149. };
  16150. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16151. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16152. return;
  16153. }
  16154. // Remove
  16155. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16156. // Bind last to it
  16157. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16158. // Bind to dummy
  16159. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16160. };
  16161. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16162. if (!internalTexture) {
  16163. return -1;
  16164. }
  16165. internalTexture._initialSlot = channel;
  16166. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16167. if (channel !== internalTexture._designatedSlot) {
  16168. this._textureCollisions.addCount(1, false);
  16169. }
  16170. }
  16171. else {
  16172. if (channel !== internalTexture._designatedSlot) {
  16173. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16174. return internalTexture._designatedSlot;
  16175. }
  16176. else {
  16177. // No slot for this texture, let's pick a new one (if we find a free slot)
  16178. if (this._nextFreeTextureSlots.length) {
  16179. return this._nextFreeTextureSlots[0];
  16180. }
  16181. // We need to recycle the oldest bound texture, sorry.
  16182. this._textureCollisions.addCount(1, false);
  16183. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16184. }
  16185. }
  16186. }
  16187. return channel;
  16188. };
  16189. Engine.prototype._linkTrackers = function (previous, next) {
  16190. previous.next = next;
  16191. next.previous = previous;
  16192. };
  16193. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16194. var currentSlot = internalTexture._designatedSlot;
  16195. if (currentSlot === -1) {
  16196. return -1;
  16197. }
  16198. internalTexture._designatedSlot = -1;
  16199. if (this.disableTextureBindingOptimization) {
  16200. return -1;
  16201. }
  16202. // Remove from bound list
  16203. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16204. // Free the slot
  16205. this._boundTexturesCache[currentSlot] = null;
  16206. this._nextFreeTextureSlots.push(currentSlot);
  16207. return currentSlot;
  16208. };
  16209. Engine.prototype._activateCurrentTexture = function () {
  16210. if (this._currentTextureChannel !== this._activeChannel) {
  16211. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16212. this._currentTextureChannel = this._activeChannel;
  16213. }
  16214. };
  16215. /** @hidden */
  16216. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16217. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16218. if (force === void 0) { force = false; }
  16219. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16220. this._activeChannel = texture._designatedSlot;
  16221. }
  16222. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16223. var isTextureForRendering = texture && texture._initialSlot > -1;
  16224. if (currentTextureBound !== texture || force) {
  16225. if (currentTextureBound) {
  16226. this._removeDesignatedSlot(currentTextureBound);
  16227. }
  16228. this._activateCurrentTexture();
  16229. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16230. this._boundTexturesCache[this._activeChannel] = texture;
  16231. if (texture) {
  16232. if (!this.disableTextureBindingOptimization) {
  16233. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16234. if (slotIndex > -1) {
  16235. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16236. }
  16237. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16238. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16239. }
  16240. texture._designatedSlot = this._activeChannel;
  16241. }
  16242. }
  16243. else if (forTextureDataUpdate) {
  16244. this._activateCurrentTexture();
  16245. }
  16246. if (isTextureForRendering && !forTextureDataUpdate) {
  16247. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16248. }
  16249. };
  16250. /** @hidden */
  16251. Engine.prototype._bindTexture = function (channel, texture) {
  16252. if (channel < 0) {
  16253. return;
  16254. }
  16255. if (texture) {
  16256. channel = this._getCorrectTextureChannel(channel, texture);
  16257. }
  16258. this._activeChannel = channel;
  16259. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16260. };
  16261. /**
  16262. * Sets a texture to the webGL context from a postprocess
  16263. * @param channel defines the channel to use
  16264. * @param postProcess defines the source postprocess
  16265. */
  16266. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16267. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16268. };
  16269. /**
  16270. * Binds the output of the passed in post process to the texture channel specified
  16271. * @param channel The channel the texture should be bound to
  16272. * @param postProcess The post process which's output should be bound
  16273. */
  16274. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16275. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16276. };
  16277. /**
  16278. * Unbind all textures from the webGL context
  16279. */
  16280. Engine.prototype.unbindAllTextures = function () {
  16281. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16282. this._activeChannel = channel;
  16283. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16285. if (this.webGLVersion > 1) {
  16286. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16287. }
  16288. }
  16289. };
  16290. /**
  16291. * Sets a texture to the according uniform.
  16292. * @param channel The texture channel
  16293. * @param uniform The uniform to set
  16294. * @param texture The texture to apply
  16295. */
  16296. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16297. if (channel < 0) {
  16298. return;
  16299. }
  16300. if (uniform) {
  16301. this._boundUniforms[channel] = uniform;
  16302. }
  16303. this._setTexture(channel, texture);
  16304. };
  16305. /**
  16306. * Sets a depth stencil texture from a render target to the according uniform.
  16307. * @param channel The texture channel
  16308. * @param uniform The uniform to set
  16309. * @param texture The render target texture containing the depth stencil texture to apply
  16310. */
  16311. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16312. if (channel < 0) {
  16313. return;
  16314. }
  16315. if (uniform) {
  16316. this._boundUniforms[channel] = uniform;
  16317. }
  16318. if (!texture || !texture.depthStencilTexture) {
  16319. this._setTexture(channel, null);
  16320. }
  16321. else {
  16322. this._setTexture(channel, texture, false, true);
  16323. }
  16324. };
  16325. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16326. var uniform = this._boundUniforms[sourceSlot];
  16327. if (uniform._currentState === destination) {
  16328. return;
  16329. }
  16330. this._gl.uniform1i(uniform, destination);
  16331. uniform._currentState = destination;
  16332. };
  16333. Engine.prototype._getTextureWrapMode = function (mode) {
  16334. switch (mode) {
  16335. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16336. return this._gl.REPEAT;
  16337. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16338. return this._gl.CLAMP_TO_EDGE;
  16339. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16340. return this._gl.MIRRORED_REPEAT;
  16341. }
  16342. return this._gl.REPEAT;
  16343. };
  16344. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16345. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16346. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16347. // Not ready?
  16348. if (!texture) {
  16349. if (this._boundTexturesCache[channel] != null) {
  16350. this._activeChannel = channel;
  16351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16353. if (this.webGLVersion > 1) {
  16354. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16355. }
  16356. }
  16357. return false;
  16358. }
  16359. // Video
  16360. if (texture.video) {
  16361. this._activeChannel = channel;
  16362. texture.update();
  16363. }
  16364. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16365. texture.delayLoad();
  16366. return false;
  16367. }
  16368. var internalTexture;
  16369. if (depthStencilTexture) {
  16370. internalTexture = texture.depthStencilTexture;
  16371. }
  16372. else if (texture.isReady()) {
  16373. internalTexture = texture.getInternalTexture();
  16374. }
  16375. else if (texture.isCube) {
  16376. internalTexture = this.emptyCubeTexture;
  16377. }
  16378. else if (texture.is3D) {
  16379. internalTexture = this.emptyTexture3D;
  16380. }
  16381. else {
  16382. internalTexture = this.emptyTexture;
  16383. }
  16384. if (!isPartOfTextureArray) {
  16385. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16386. }
  16387. var needToBind = true;
  16388. if (this._boundTexturesCache[channel] === internalTexture) {
  16389. this._moveBoundTextureOnTop(internalTexture);
  16390. if (!isPartOfTextureArray) {
  16391. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16392. }
  16393. needToBind = false;
  16394. }
  16395. this._activeChannel = channel;
  16396. if (internalTexture && internalTexture.is3D) {
  16397. if (needToBind) {
  16398. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16401. internalTexture._cachedWrapU = texture.wrapU;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16403. }
  16404. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16405. internalTexture._cachedWrapV = texture.wrapV;
  16406. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16407. }
  16408. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16409. internalTexture._cachedWrapR = texture.wrapR;
  16410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16411. }
  16412. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16413. }
  16414. else if (internalTexture && internalTexture.isCube) {
  16415. if (needToBind) {
  16416. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16417. }
  16418. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16419. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16420. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16421. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16422. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16424. }
  16425. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16426. }
  16427. else {
  16428. if (needToBind) {
  16429. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16430. }
  16431. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16432. internalTexture._cachedWrapU = texture.wrapU;
  16433. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16434. }
  16435. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16436. internalTexture._cachedWrapV = texture.wrapV;
  16437. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16438. }
  16439. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16440. }
  16441. return true;
  16442. };
  16443. /**
  16444. * Sets an array of texture to the webGL context
  16445. * @param channel defines the channel where the texture array must be set
  16446. * @param uniform defines the associated uniform location
  16447. * @param textures defines the array of textures to bind
  16448. */
  16449. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16450. if (channel < 0 || !uniform) {
  16451. return;
  16452. }
  16453. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16454. this._textureUnits = new Int32Array(textures.length);
  16455. }
  16456. for (var i = 0; i < textures.length; i++) {
  16457. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16458. }
  16459. this._gl.uniform1iv(uniform, this._textureUnits);
  16460. for (var index = 0; index < textures.length; index++) {
  16461. this._setTexture(this._textureUnits[index], textures[index], true);
  16462. }
  16463. };
  16464. /** @hidden */
  16465. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16466. var internalTexture = texture.getInternalTexture();
  16467. if (!internalTexture) {
  16468. return;
  16469. }
  16470. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16471. var value = texture.anisotropicFilteringLevel;
  16472. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16473. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16474. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16475. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16476. }
  16477. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16478. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16479. internalTexture._cachedAnisotropicFilteringLevel = value;
  16480. }
  16481. };
  16482. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16483. this._bindTextureDirectly(target, texture, true, true);
  16484. this._gl.texParameterf(target, parameter, value);
  16485. };
  16486. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16487. if (texture) {
  16488. this._bindTextureDirectly(target, texture, true, true);
  16489. }
  16490. this._gl.texParameteri(target, parameter, value);
  16491. };
  16492. /**
  16493. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16494. * @param x defines the x coordinate of the rectangle where pixels must be read
  16495. * @param y defines the y coordinate of the rectangle where pixels must be read
  16496. * @param width defines the width of the rectangle where pixels must be read
  16497. * @param height defines the height of the rectangle where pixels must be read
  16498. * @returns a Uint8Array containing RGBA colors
  16499. */
  16500. Engine.prototype.readPixels = function (x, y, width, height) {
  16501. var data = new Uint8Array(height * width * 4);
  16502. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16503. return data;
  16504. };
  16505. /**
  16506. * Add an externaly attached data from its key.
  16507. * This method call will fail and return false, if such key already exists.
  16508. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16509. * @param key the unique key that identifies the data
  16510. * @param data the data object to associate to the key for this Engine instance
  16511. * @return true if no such key were already present and the data was added successfully, false otherwise
  16512. */
  16513. Engine.prototype.addExternalData = function (key, data) {
  16514. if (!this._externalData) {
  16515. this._externalData = new BABYLON.StringDictionary();
  16516. }
  16517. return this._externalData.add(key, data);
  16518. };
  16519. /**
  16520. * Get an externaly attached data from its key
  16521. * @param key the unique key that identifies the data
  16522. * @return the associated data, if present (can be null), or undefined if not present
  16523. */
  16524. Engine.prototype.getExternalData = function (key) {
  16525. if (!this._externalData) {
  16526. this._externalData = new BABYLON.StringDictionary();
  16527. }
  16528. return this._externalData.get(key);
  16529. };
  16530. /**
  16531. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16532. * @param key the unique key that identifies the data
  16533. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16534. * @return the associated data, can be null if the factory returned null.
  16535. */
  16536. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16537. if (!this._externalData) {
  16538. this._externalData = new BABYLON.StringDictionary();
  16539. }
  16540. return this._externalData.getOrAddWithFactory(key, factory);
  16541. };
  16542. /**
  16543. * Remove an externaly attached data from the Engine instance
  16544. * @param key the unique key that identifies the data
  16545. * @return true if the data was successfully removed, false if it doesn't exist
  16546. */
  16547. Engine.prototype.removeExternalData = function (key) {
  16548. if (!this._externalData) {
  16549. this._externalData = new BABYLON.StringDictionary();
  16550. }
  16551. return this._externalData.remove(key);
  16552. };
  16553. /**
  16554. * Unbind all vertex attributes from the webGL context
  16555. */
  16556. Engine.prototype.unbindAllAttributes = function () {
  16557. if (this._mustWipeVertexAttributes) {
  16558. this._mustWipeVertexAttributes = false;
  16559. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16560. this._gl.disableVertexAttribArray(i);
  16561. this._vertexAttribArraysEnabled[i] = false;
  16562. this._currentBufferPointers[i].active = false;
  16563. }
  16564. return;
  16565. }
  16566. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16567. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16568. continue;
  16569. }
  16570. this._gl.disableVertexAttribArray(i);
  16571. this._vertexAttribArraysEnabled[i] = false;
  16572. this._currentBufferPointers[i].active = false;
  16573. }
  16574. };
  16575. /**
  16576. * 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
  16577. */
  16578. Engine.prototype.releaseEffects = function () {
  16579. for (var name in this._compiledEffects) {
  16580. this._deleteProgram(this._compiledEffects[name]._program);
  16581. }
  16582. this._compiledEffects = {};
  16583. };
  16584. /**
  16585. * Dispose and release all associated resources
  16586. */
  16587. Engine.prototype.dispose = function () {
  16588. this.hideLoadingUI();
  16589. this.stopRenderLoop();
  16590. // Release postProcesses
  16591. while (this.postProcesses.length) {
  16592. this.postProcesses[0].dispose();
  16593. }
  16594. // Empty texture
  16595. if (this._emptyTexture) {
  16596. this._releaseTexture(this._emptyTexture);
  16597. this._emptyTexture = null;
  16598. }
  16599. if (this._emptyCubeTexture) {
  16600. this._releaseTexture(this._emptyCubeTexture);
  16601. this._emptyCubeTexture = null;
  16602. }
  16603. // Rescale PP
  16604. if (this._rescalePostProcess) {
  16605. this._rescalePostProcess.dispose();
  16606. }
  16607. // Release scenes
  16608. while (this.scenes.length) {
  16609. this.scenes[0].dispose();
  16610. }
  16611. // Release audio engine
  16612. if (Engine.audioEngine) {
  16613. Engine.audioEngine.dispose();
  16614. }
  16615. // Release effects
  16616. this.releaseEffects();
  16617. // Unbind
  16618. this.unbindAllAttributes();
  16619. this._boundUniforms = [];
  16620. if (this._dummyFramebuffer) {
  16621. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16622. }
  16623. //WebVR
  16624. this.disableVR();
  16625. // Events
  16626. if (BABYLON.Tools.IsWindowObjectExist()) {
  16627. window.removeEventListener("blur", this._onBlur);
  16628. window.removeEventListener("focus", this._onFocus);
  16629. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16630. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16631. if (this._renderingCanvas) {
  16632. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16633. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16634. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16635. if (!this._doNotHandleContextLost) {
  16636. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16637. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16638. }
  16639. }
  16640. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16641. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16642. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16643. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16644. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16645. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16646. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16647. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16648. if (this._onVrDisplayConnect) {
  16649. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16650. if (this._onVrDisplayDisconnect) {
  16651. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16652. }
  16653. if (this._onVrDisplayPresentChange) {
  16654. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16655. }
  16656. this._onVrDisplayConnect = null;
  16657. this._onVrDisplayDisconnect = null;
  16658. }
  16659. }
  16660. // Remove from Instances
  16661. var index = Engine.Instances.indexOf(this);
  16662. if (index >= 0) {
  16663. Engine.Instances.splice(index, 1);
  16664. }
  16665. this._workingCanvas = null;
  16666. this._workingContext = null;
  16667. this._currentBufferPointers = [];
  16668. this._renderingCanvas = null;
  16669. this._currentProgram = null;
  16670. this._bindedRenderFunction = null;
  16671. this.onResizeObservable.clear();
  16672. this.onCanvasBlurObservable.clear();
  16673. this.onCanvasFocusObservable.clear();
  16674. this.onCanvasPointerOutObservable.clear();
  16675. this.onBeginFrameObservable.clear();
  16676. this.onEndFrameObservable.clear();
  16677. BABYLON.Effect.ResetCache();
  16678. // Abort active requests
  16679. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16680. var request = _a[_i];
  16681. request.abort();
  16682. }
  16683. };
  16684. // Loading screen
  16685. /**
  16686. * Display the loading screen
  16687. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16688. */
  16689. Engine.prototype.displayLoadingUI = function () {
  16690. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16691. return;
  16692. }
  16693. var loadingScreen = this.loadingScreen;
  16694. if (loadingScreen) {
  16695. loadingScreen.displayLoadingUI();
  16696. }
  16697. };
  16698. /**
  16699. * Hide the loading screen
  16700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16701. */
  16702. Engine.prototype.hideLoadingUI = function () {
  16703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16704. return;
  16705. }
  16706. var loadingScreen = this.loadingScreen;
  16707. if (loadingScreen) {
  16708. loadingScreen.hideLoadingUI();
  16709. }
  16710. };
  16711. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16712. /**
  16713. * Gets the current loading screen object
  16714. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16715. */
  16716. get: function () {
  16717. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16718. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16719. return this._loadingScreen;
  16720. },
  16721. /**
  16722. * Sets the current loading screen object
  16723. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16724. */
  16725. set: function (loadingScreen) {
  16726. this._loadingScreen = loadingScreen;
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16732. /**
  16733. * Sets the current loading screen text
  16734. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16735. */
  16736. set: function (text) {
  16737. this.loadingScreen.loadingUIText = text;
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16743. /**
  16744. * Sets the current loading screen background color
  16745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16746. */
  16747. set: function (color) {
  16748. this.loadingScreen.loadingUIBackgroundColor = color;
  16749. },
  16750. enumerable: true,
  16751. configurable: true
  16752. });
  16753. /**
  16754. * Attach a new callback raised when context lost event is fired
  16755. * @param callback defines the callback to call
  16756. */
  16757. Engine.prototype.attachContextLostEvent = function (callback) {
  16758. if (this._renderingCanvas) {
  16759. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16760. }
  16761. };
  16762. /**
  16763. * Attach a new callback raised when context restored event is fired
  16764. * @param callback defines the callback to call
  16765. */
  16766. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16767. if (this._renderingCanvas) {
  16768. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16769. }
  16770. };
  16771. /**
  16772. * Gets the source code of the vertex shader associated with a specific webGL program
  16773. * @param program defines the program to use
  16774. * @returns a string containing the source code of the vertex shader associated with the program
  16775. */
  16776. Engine.prototype.getVertexShaderSource = function (program) {
  16777. var shaders = this._gl.getAttachedShaders(program);
  16778. if (!shaders) {
  16779. return null;
  16780. }
  16781. return this._gl.getShaderSource(shaders[0]);
  16782. };
  16783. /**
  16784. * Gets the source code of the fragment shader associated with a specific webGL program
  16785. * @param program defines the program to use
  16786. * @returns a string containing the source code of the fragment shader associated with the program
  16787. */
  16788. Engine.prototype.getFragmentShaderSource = function (program) {
  16789. var shaders = this._gl.getAttachedShaders(program);
  16790. if (!shaders) {
  16791. return null;
  16792. }
  16793. return this._gl.getShaderSource(shaders[1]);
  16794. };
  16795. /**
  16796. * Get the current error code of the webGL context
  16797. * @returns the error code
  16798. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16799. */
  16800. Engine.prototype.getError = function () {
  16801. return this._gl.getError();
  16802. };
  16803. // FPS
  16804. /**
  16805. * Gets the current framerate
  16806. * @returns a number representing the framerate
  16807. */
  16808. Engine.prototype.getFps = function () {
  16809. return this._fps;
  16810. };
  16811. /**
  16812. * Gets the time spent between current and previous frame
  16813. * @returns a number representing the delta time in ms
  16814. */
  16815. Engine.prototype.getDeltaTime = function () {
  16816. return this._deltaTime;
  16817. };
  16818. Engine.prototype._measureFps = function () {
  16819. this._performanceMonitor.sampleFrame();
  16820. this._fps = this._performanceMonitor.averageFPS;
  16821. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16822. };
  16823. /** @hidden */
  16824. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16825. if (faceIndex === void 0) { faceIndex = -1; }
  16826. var gl = this._gl;
  16827. if (!this._dummyFramebuffer) {
  16828. var dummy = gl.createFramebuffer();
  16829. if (!dummy) {
  16830. throw new Error("Unable to create dummy framebuffer");
  16831. }
  16832. this._dummyFramebuffer = dummy;
  16833. }
  16834. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16835. if (faceIndex > -1) {
  16836. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16837. }
  16838. else {
  16839. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16840. }
  16841. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16842. var buffer;
  16843. switch (readType) {
  16844. case gl.UNSIGNED_BYTE:
  16845. buffer = new Uint8Array(4 * width * height);
  16846. readType = gl.UNSIGNED_BYTE;
  16847. break;
  16848. default:
  16849. buffer = new Float32Array(4 * width * height);
  16850. readType = gl.FLOAT;
  16851. break;
  16852. }
  16853. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16854. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16855. return buffer;
  16856. };
  16857. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16858. if (this._webGLVersion > 1) {
  16859. return this._caps.colorBufferFloat;
  16860. }
  16861. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16862. };
  16863. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16864. if (this._webGLVersion > 1) {
  16865. return this._caps.colorBufferFloat;
  16866. }
  16867. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16868. };
  16869. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16870. Engine.prototype._canRenderToFramebuffer = function (type) {
  16871. var gl = this._gl;
  16872. //clear existing errors
  16873. while (gl.getError() !== gl.NO_ERROR) { }
  16874. var successful = true;
  16875. var texture = gl.createTexture();
  16876. gl.bindTexture(gl.TEXTURE_2D, texture);
  16877. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16880. var fb = gl.createFramebuffer();
  16881. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16882. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16883. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16884. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16885. successful = successful && (gl.getError() === gl.NO_ERROR);
  16886. //try render by clearing frame buffer's color buffer
  16887. if (successful) {
  16888. gl.clear(gl.COLOR_BUFFER_BIT);
  16889. successful = successful && (gl.getError() === gl.NO_ERROR);
  16890. }
  16891. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16892. if (successful) {
  16893. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16894. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16895. var readFormat = gl.RGBA;
  16896. var readType = gl.UNSIGNED_BYTE;
  16897. var buffer = new Uint8Array(4);
  16898. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16899. successful = successful && (gl.getError() === gl.NO_ERROR);
  16900. }
  16901. //clean up
  16902. gl.deleteTexture(texture);
  16903. gl.deleteFramebuffer(fb);
  16904. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16905. //clear accumulated errors
  16906. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16907. return successful;
  16908. };
  16909. /** @hidden */
  16910. Engine.prototype._getWebGLTextureType = function (type) {
  16911. if (type === Engine.TEXTURETYPE_FLOAT) {
  16912. return this._gl.FLOAT;
  16913. }
  16914. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16915. // Add Half Float Constant.
  16916. return this._gl.HALF_FLOAT_OES;
  16917. }
  16918. return this._gl.UNSIGNED_BYTE;
  16919. };
  16920. ;
  16921. Engine.prototype._getInternalFormat = function (format) {
  16922. var internalFormat = this._gl.RGBA;
  16923. switch (format) {
  16924. case Engine.TEXTUREFORMAT_ALPHA:
  16925. internalFormat = this._gl.ALPHA;
  16926. break;
  16927. case Engine.TEXTUREFORMAT_LUMINANCE:
  16928. internalFormat = this._gl.LUMINANCE;
  16929. break;
  16930. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16931. internalFormat = this._gl.LUMINANCE_ALPHA;
  16932. break;
  16933. case Engine.TEXTUREFORMAT_RGB:
  16934. case Engine.TEXTUREFORMAT_RGB32F:
  16935. internalFormat = this._gl.RGB;
  16936. break;
  16937. case Engine.TEXTUREFORMAT_RGBA:
  16938. case Engine.TEXTUREFORMAT_RGBA32F:
  16939. internalFormat = this._gl.RGBA;
  16940. break;
  16941. case Engine.TEXTUREFORMAT_R32F:
  16942. internalFormat = this._gl.RED;
  16943. break;
  16944. case Engine.TEXTUREFORMAT_RG32F:
  16945. internalFormat = this._gl.RG;
  16946. break;
  16947. }
  16948. return internalFormat;
  16949. };
  16950. /** @hidden */
  16951. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16952. if (this._webGLVersion === 1) {
  16953. if (format) {
  16954. switch (format) {
  16955. case Engine.TEXTUREFORMAT_LUMINANCE:
  16956. return this._gl.LUMINANCE;
  16957. }
  16958. }
  16959. return this._gl.RGBA;
  16960. }
  16961. if (type === Engine.TEXTURETYPE_FLOAT) {
  16962. if (format) {
  16963. switch (format) {
  16964. case Engine.TEXTUREFORMAT_R32F:
  16965. return this._gl.R32F;
  16966. case Engine.TEXTUREFORMAT_RG32F:
  16967. return this._gl.RG32F;
  16968. case Engine.TEXTUREFORMAT_RGB32F:
  16969. return this._gl.RGB32F;
  16970. }
  16971. }
  16972. return this._gl.RGBA32F;
  16973. }
  16974. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16975. return this._gl.RGBA16F;
  16976. }
  16977. if (format) {
  16978. switch (format) {
  16979. case Engine.TEXTUREFORMAT_LUMINANCE:
  16980. return this._gl.LUMINANCE;
  16981. case Engine.TEXTUREFORMAT_RGB:
  16982. return this._gl.RGB;
  16983. }
  16984. }
  16985. return this._gl.RGBA;
  16986. };
  16987. ;
  16988. /** @hidden */
  16989. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16990. if (type === Engine.TEXTURETYPE_FLOAT) {
  16991. return this._gl.RGBA32F;
  16992. }
  16993. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16994. return this._gl.RGBA16F;
  16995. }
  16996. return this._gl.RGBA8;
  16997. };
  16998. ;
  16999. /**
  17000. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17001. * @return the new query
  17002. */
  17003. Engine.prototype.createQuery = function () {
  17004. return this._gl.createQuery();
  17005. };
  17006. /**
  17007. * Delete and release a webGL query
  17008. * @param query defines the query to delete
  17009. * @return the current engine
  17010. */
  17011. Engine.prototype.deleteQuery = function (query) {
  17012. this._gl.deleteQuery(query);
  17013. return this;
  17014. };
  17015. /**
  17016. * Check if a given query has resolved and got its value
  17017. * @param query defines the query to check
  17018. * @returns true if the query got its value
  17019. */
  17020. Engine.prototype.isQueryResultAvailable = function (query) {
  17021. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17022. };
  17023. /**
  17024. * Gets the value of a given query
  17025. * @param query defines the query to check
  17026. * @returns the value of the query
  17027. */
  17028. Engine.prototype.getQueryResult = function (query) {
  17029. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17030. };
  17031. /**
  17032. * Initiates an occlusion query
  17033. * @param algorithmType defines the algorithm to use
  17034. * @param query defines the query to use
  17035. * @returns the current engine
  17036. * @see http://doc.babylonjs.com/features/occlusionquery
  17037. */
  17038. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17039. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17040. this._gl.beginQuery(glAlgorithm, query);
  17041. return this;
  17042. };
  17043. /**
  17044. * Ends an occlusion query
  17045. * @see http://doc.babylonjs.com/features/occlusionquery
  17046. * @param algorithmType defines the algorithm to use
  17047. * @returns the current engine
  17048. */
  17049. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17050. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17051. this._gl.endQuery(glAlgorithm);
  17052. return this;
  17053. };
  17054. /* Time queries */
  17055. Engine.prototype._createTimeQuery = function () {
  17056. var timerQuery = this._caps.timerQuery;
  17057. if (timerQuery.createQueryEXT) {
  17058. return timerQuery.createQueryEXT();
  17059. }
  17060. return this.createQuery();
  17061. };
  17062. Engine.prototype._deleteTimeQuery = function (query) {
  17063. var timerQuery = this._caps.timerQuery;
  17064. if (timerQuery.deleteQueryEXT) {
  17065. timerQuery.deleteQueryEXT(query);
  17066. return;
  17067. }
  17068. this.deleteQuery(query);
  17069. };
  17070. Engine.prototype._getTimeQueryResult = function (query) {
  17071. var timerQuery = this._caps.timerQuery;
  17072. if (timerQuery.getQueryObjectEXT) {
  17073. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17074. }
  17075. return this.getQueryResult(query);
  17076. };
  17077. Engine.prototype._getTimeQueryAvailability = function (query) {
  17078. var timerQuery = this._caps.timerQuery;
  17079. if (timerQuery.getQueryObjectEXT) {
  17080. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17081. }
  17082. return this.isQueryResultAvailable(query);
  17083. };
  17084. /**
  17085. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17086. * Please note that only one query can be issued at a time
  17087. * @returns a time token used to track the time span
  17088. */
  17089. Engine.prototype.startTimeQuery = function () {
  17090. var timerQuery = this._caps.timerQuery;
  17091. if (!timerQuery) {
  17092. return null;
  17093. }
  17094. var token = new BABYLON._TimeToken();
  17095. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17096. if (this._caps.canUseTimestampForTimerQuery) {
  17097. token._startTimeQuery = this._createTimeQuery();
  17098. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17099. }
  17100. else {
  17101. if (this._currentNonTimestampToken) {
  17102. return this._currentNonTimestampToken;
  17103. }
  17104. token._timeElapsedQuery = this._createTimeQuery();
  17105. if (timerQuery.beginQueryEXT) {
  17106. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17107. }
  17108. else {
  17109. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17110. }
  17111. this._currentNonTimestampToken = token;
  17112. }
  17113. return token;
  17114. };
  17115. /**
  17116. * Ends a time query
  17117. * @param token defines the token used to measure the time span
  17118. * @returns the time spent (in ns)
  17119. */
  17120. Engine.prototype.endTimeQuery = function (token) {
  17121. var timerQuery = this._caps.timerQuery;
  17122. if (!timerQuery || !token) {
  17123. return -1;
  17124. }
  17125. if (this._caps.canUseTimestampForTimerQuery) {
  17126. if (!token._startTimeQuery) {
  17127. return -1;
  17128. }
  17129. if (!token._endTimeQuery) {
  17130. token._endTimeQuery = this._createTimeQuery();
  17131. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17132. }
  17133. }
  17134. else if (!token._timeElapsedQueryEnded) {
  17135. if (!token._timeElapsedQuery) {
  17136. return -1;
  17137. }
  17138. if (timerQuery.endQueryEXT) {
  17139. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17140. }
  17141. else {
  17142. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17143. }
  17144. token._timeElapsedQueryEnded = true;
  17145. }
  17146. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17147. var available = false;
  17148. if (token._endTimeQuery) {
  17149. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17150. }
  17151. else if (token._timeElapsedQuery) {
  17152. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17153. }
  17154. if (available && !disjoint) {
  17155. var result = 0;
  17156. if (this._caps.canUseTimestampForTimerQuery) {
  17157. if (!token._startTimeQuery || !token._endTimeQuery) {
  17158. return -1;
  17159. }
  17160. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17161. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17162. result = timeEnd - timeStart;
  17163. this._deleteTimeQuery(token._startTimeQuery);
  17164. this._deleteTimeQuery(token._endTimeQuery);
  17165. token._startTimeQuery = null;
  17166. token._endTimeQuery = null;
  17167. }
  17168. else {
  17169. if (!token._timeElapsedQuery) {
  17170. return -1;
  17171. }
  17172. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17173. this._deleteTimeQuery(token._timeElapsedQuery);
  17174. token._timeElapsedQuery = null;
  17175. token._timeElapsedQueryEnded = false;
  17176. this._currentNonTimestampToken = null;
  17177. }
  17178. return result;
  17179. }
  17180. return -1;
  17181. };
  17182. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17183. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17184. };
  17185. // Transform feedback
  17186. /**
  17187. * Creates a webGL transform feedback object
  17188. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17189. * @returns the webGL transform feedback object
  17190. */
  17191. Engine.prototype.createTransformFeedback = function () {
  17192. return this._gl.createTransformFeedback();
  17193. };
  17194. /**
  17195. * Delete a webGL transform feedback object
  17196. * @param value defines the webGL transform feedback object to delete
  17197. */
  17198. Engine.prototype.deleteTransformFeedback = function (value) {
  17199. this._gl.deleteTransformFeedback(value);
  17200. };
  17201. /**
  17202. * Bind a webGL transform feedback object to the webgl context
  17203. * @param value defines the webGL transform feedback object to bind
  17204. */
  17205. Engine.prototype.bindTransformFeedback = function (value) {
  17206. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17207. };
  17208. /**
  17209. * Begins a transform feedback operation
  17210. * @param usePoints defines if points or triangles must be used
  17211. */
  17212. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17213. if (usePoints === void 0) { usePoints = true; }
  17214. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17215. };
  17216. /**
  17217. * Ends a transform feedback operation
  17218. */
  17219. Engine.prototype.endTransformFeedback = function () {
  17220. this._gl.endTransformFeedback();
  17221. };
  17222. /**
  17223. * Specify the varyings to use with transform feedback
  17224. * @param program defines the associated webGL program
  17225. * @param value defines the list of strings representing the varying names
  17226. */
  17227. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17228. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17229. };
  17230. /**
  17231. * Bind a webGL buffer for a transform feedback operation
  17232. * @param value defines the webGL buffer to bind
  17233. */
  17234. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17235. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17236. };
  17237. /** @hidden */
  17238. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17239. var _this = this;
  17240. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17241. this._activeRequests.push(request);
  17242. request.onCompleteObservable.add(function (request) {
  17243. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17244. });
  17245. return request;
  17246. };
  17247. /** @hidden */
  17248. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17249. var _this = this;
  17250. return new Promise(function (resolve, reject) {
  17251. _this._loadFile(url, function (data) {
  17252. resolve(data);
  17253. }, undefined, database, useArrayBuffer, function (request, exception) {
  17254. reject(exception);
  17255. });
  17256. });
  17257. };
  17258. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17259. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17260. var onload = function (data) {
  17261. loadedFiles[index] = data;
  17262. loadedFiles._internalCount++;
  17263. if (loadedFiles._internalCount === 6) {
  17264. onfinish(loadedFiles);
  17265. }
  17266. };
  17267. var onerror = function (request, exception) {
  17268. if (onErrorCallBack && request) {
  17269. onErrorCallBack(request.status + " " + request.statusText, exception);
  17270. }
  17271. };
  17272. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17273. };
  17274. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17275. if (onError === void 0) { onError = null; }
  17276. var loadedFiles = [];
  17277. loadedFiles._internalCount = 0;
  17278. for (var index = 0; index < 6; index++) {
  17279. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17280. }
  17281. };
  17282. // Statics
  17283. /**
  17284. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17285. * @returns true if the engine can be created
  17286. * @ignorenaming
  17287. */
  17288. Engine.isSupported = function () {
  17289. try {
  17290. var tempcanvas = document.createElement("canvas");
  17291. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17292. return gl != null && !!window.WebGLRenderingContext;
  17293. }
  17294. catch (e) {
  17295. return false;
  17296. }
  17297. };
  17298. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17299. Engine.ExceptionList = [
  17300. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17301. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17302. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17303. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17304. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17305. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17306. ];
  17307. /** Gets the list of created engines */
  17308. Engine.Instances = new Array();
  17309. // Const statics
  17310. Engine._ALPHA_DISABLE = 0;
  17311. Engine._ALPHA_ADD = 1;
  17312. Engine._ALPHA_COMBINE = 2;
  17313. Engine._ALPHA_SUBTRACT = 3;
  17314. Engine._ALPHA_MULTIPLY = 4;
  17315. Engine._ALPHA_MAXIMIZED = 5;
  17316. Engine._ALPHA_ONEONE = 6;
  17317. Engine._ALPHA_PREMULTIPLIED = 7;
  17318. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17319. Engine._ALPHA_INTERPOLATE = 9;
  17320. Engine._ALPHA_SCREENMODE = 10;
  17321. Engine._DELAYLOADSTATE_NONE = 0;
  17322. Engine._DELAYLOADSTATE_LOADED = 1;
  17323. Engine._DELAYLOADSTATE_LOADING = 2;
  17324. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17325. Engine._TEXTUREFORMAT_ALPHA = 0;
  17326. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17327. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17328. Engine._TEXTUREFORMAT_RGB = 4;
  17329. Engine._TEXTUREFORMAT_RGBA = 5;
  17330. Engine._TEXTUREFORMAT_R32F = 6;
  17331. Engine._TEXTUREFORMAT_RG32F = 7;
  17332. Engine._TEXTUREFORMAT_RGB32F = 8;
  17333. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17334. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17335. Engine._TEXTURETYPE_FLOAT = 1;
  17336. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17337. // Depht or Stencil test Constants.
  17338. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17339. 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.
  17340. 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.
  17341. 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.
  17342. 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.
  17343. 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.
  17344. 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.
  17345. 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.
  17346. // Stencil Actions Constants.
  17347. Engine._KEEP = 0x1E00;
  17348. Engine._REPLACE = 0x1E01;
  17349. Engine._INCR = 0x1E02;
  17350. Engine._DECR = 0x1E03;
  17351. Engine._INVERT = 0x150A;
  17352. Engine._INCR_WRAP = 0x8507;
  17353. Engine._DECR_WRAP = 0x8508;
  17354. // Texture rescaling mode
  17355. Engine._SCALEMODE_FLOOR = 1;
  17356. Engine._SCALEMODE_NEAREST = 2;
  17357. Engine._SCALEMODE_CEILING = 3;
  17358. // Updatable statics so stick with vars here
  17359. /**
  17360. * Gets or sets the epsilon value used by collision engine
  17361. */
  17362. Engine.CollisionsEpsilon = 0.001;
  17363. /**
  17364. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17365. */
  17366. Engine.CodeRepository = "src/";
  17367. /**
  17368. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17369. */
  17370. Engine.ShadersRepository = "src/Shaders/";
  17371. return Engine;
  17372. }());
  17373. BABYLON.Engine = Engine;
  17374. })(BABYLON || (BABYLON = {}));
  17375. //# sourceMappingURL=babylon.engine.js.map
  17376. var BABYLON;
  17377. (function (BABYLON) {
  17378. /**
  17379. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17380. */
  17381. var Node = /** @class */ (function () {
  17382. /**
  17383. * Creates a new Node
  17384. * @param {string} name - the name and id to be given to this node
  17385. * @param {BABYLON.Scene} the scene this node will be added to
  17386. */
  17387. function Node(name, scene) {
  17388. if (scene === void 0) { scene = null; }
  17389. /**
  17390. * Gets or sets a string used to store user defined state for the node
  17391. */
  17392. this.state = "";
  17393. /**
  17394. * Gets or sets an object used to store user defined information for the node
  17395. */
  17396. this.metadata = null;
  17397. /**
  17398. * Gets or sets a boolean used to define if the node must be serialized
  17399. */
  17400. this.doNotSerialize = false;
  17401. /** @hidden */
  17402. this._isDisposed = false;
  17403. /**
  17404. * Gets a list of Animations associated with the node
  17405. */
  17406. this.animations = new Array();
  17407. this._ranges = {};
  17408. this._isEnabled = true;
  17409. this._isReady = true;
  17410. /** @hidden */
  17411. this._currentRenderId = -1;
  17412. this._parentRenderId = -1;
  17413. this._childRenderId = -1;
  17414. this._animationPropertiesOverride = null;
  17415. /**
  17416. * An event triggered when the mesh is disposed
  17417. */
  17418. this.onDisposeObservable = new BABYLON.Observable();
  17419. // Behaviors
  17420. this._behaviors = new Array();
  17421. this.name = name;
  17422. this.id = name;
  17423. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17424. this.uniqueId = this._scene.getUniqueId();
  17425. this._initCache();
  17426. }
  17427. /**
  17428. * Gets a boolean indicating if the node has been disposed
  17429. * @returns true if the node was disposed
  17430. */
  17431. Node.prototype.isDisposed = function () {
  17432. return this._isDisposed;
  17433. };
  17434. Object.defineProperty(Node.prototype, "parent", {
  17435. get: function () {
  17436. return this._parentNode;
  17437. },
  17438. /**
  17439. * Gets or sets the parent of the node
  17440. */
  17441. set: function (parent) {
  17442. if (this._parentNode === parent) {
  17443. return;
  17444. }
  17445. // Remove self from list of children of parent
  17446. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17447. var index = this._parentNode._children.indexOf(this);
  17448. if (index !== -1) {
  17449. this._parentNode._children.splice(index, 1);
  17450. }
  17451. }
  17452. // Store new parent
  17453. this._parentNode = parent;
  17454. // Add as child to new parent
  17455. if (this._parentNode) {
  17456. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17457. this._parentNode._children = new Array();
  17458. }
  17459. this._parentNode._children.push(this);
  17460. }
  17461. },
  17462. enumerable: true,
  17463. configurable: true
  17464. });
  17465. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17466. /**
  17467. * Gets or sets the animation properties override
  17468. */
  17469. get: function () {
  17470. if (!this._animationPropertiesOverride) {
  17471. return this._scene.animationPropertiesOverride;
  17472. }
  17473. return this._animationPropertiesOverride;
  17474. },
  17475. set: function (value) {
  17476. this._animationPropertiesOverride = value;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. /**
  17482. * Gets a string idenfifying the name of the class
  17483. * @returns "Node" string
  17484. */
  17485. Node.prototype.getClassName = function () {
  17486. return "Node";
  17487. };
  17488. Object.defineProperty(Node.prototype, "onDispose", {
  17489. /**
  17490. * Sets a callback that will be raised when the node will be disposed
  17491. */
  17492. set: function (callback) {
  17493. if (this._onDisposeObserver) {
  17494. this.onDisposeObservable.remove(this._onDisposeObserver);
  17495. }
  17496. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17497. },
  17498. enumerable: true,
  17499. configurable: true
  17500. });
  17501. /**
  17502. * Gets the scene of the node
  17503. * @returns a {BABYLON.Scene}
  17504. */
  17505. Node.prototype.getScene = function () {
  17506. return this._scene;
  17507. };
  17508. /**
  17509. * Gets the engine of the node
  17510. * @returns a {BABYLON.Engine}
  17511. */
  17512. Node.prototype.getEngine = function () {
  17513. return this._scene.getEngine();
  17514. };
  17515. /**
  17516. * Attach a behavior to the node
  17517. * @see http://doc.babylonjs.com/features/behaviour
  17518. * @param behavior defines the behavior to attach
  17519. * @returns the current Node
  17520. */
  17521. Node.prototype.addBehavior = function (behavior) {
  17522. var _this = this;
  17523. var index = this._behaviors.indexOf(behavior);
  17524. if (index !== -1) {
  17525. return this;
  17526. }
  17527. behavior.init();
  17528. if (this._scene.isLoading) {
  17529. // We defer the attach when the scene will be loaded
  17530. var observer = this._scene.onDataLoadedObservable.add(function () {
  17531. behavior.attach(_this);
  17532. setTimeout(function () {
  17533. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17534. _this._scene.onDataLoadedObservable.remove(observer);
  17535. }, 0);
  17536. });
  17537. }
  17538. else {
  17539. behavior.attach(this);
  17540. }
  17541. this._behaviors.push(behavior);
  17542. return this;
  17543. };
  17544. /**
  17545. * Remove an attached behavior
  17546. * @see http://doc.babylonjs.com/features/behaviour
  17547. * @param behavior defines the behavior to attach
  17548. * @returns the current Node
  17549. */
  17550. Node.prototype.removeBehavior = function (behavior) {
  17551. var index = this._behaviors.indexOf(behavior);
  17552. if (index === -1) {
  17553. return this;
  17554. }
  17555. this._behaviors[index].detach();
  17556. this._behaviors.splice(index, 1);
  17557. return this;
  17558. };
  17559. Object.defineProperty(Node.prototype, "behaviors", {
  17560. /**
  17561. * Gets the list of attached behaviors
  17562. * @see http://doc.babylonjs.com/features/behaviour
  17563. */
  17564. get: function () {
  17565. return this._behaviors;
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. /**
  17571. * Gets an attached behavior by name
  17572. * @param name defines the name of the behavior to look for
  17573. * @see http://doc.babylonjs.com/features/behaviour
  17574. * @returns null if behavior was not found else the requested behavior
  17575. */
  17576. Node.prototype.getBehaviorByName = function (name) {
  17577. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17578. var behavior = _a[_i];
  17579. if (behavior.name === name) {
  17580. return behavior;
  17581. }
  17582. }
  17583. return null;
  17584. };
  17585. /**
  17586. * Returns the world matrix of the node
  17587. * @returns a matrix containing the node's world matrix
  17588. */
  17589. Node.prototype.getWorldMatrix = function () {
  17590. return BABYLON.Matrix.Identity();
  17591. };
  17592. /** @hidden */
  17593. Node.prototype._getWorldMatrixDeterminant = function () {
  17594. return 1;
  17595. };
  17596. // override it in derived class if you add new variables to the cache
  17597. // and call the parent class method
  17598. /** @hidden */
  17599. Node.prototype._initCache = function () {
  17600. this._cache = {};
  17601. this._cache.parent = undefined;
  17602. };
  17603. /** @hidden */
  17604. Node.prototype.updateCache = function (force) {
  17605. if (!force && this.isSynchronized())
  17606. return;
  17607. this._cache.parent = this.parent;
  17608. this._updateCache();
  17609. };
  17610. // override it in derived class if you add new variables to the cache
  17611. // and call the parent class method if !ignoreParentClass
  17612. /** @hidden */
  17613. Node.prototype._updateCache = function (ignoreParentClass) {
  17614. };
  17615. // override it in derived class if you add new variables to the cache
  17616. /** @hidden */
  17617. Node.prototype._isSynchronized = function () {
  17618. return true;
  17619. };
  17620. /** @hidden */
  17621. Node.prototype._markSyncedWithParent = function () {
  17622. if (this.parent) {
  17623. this._parentRenderId = this.parent._childRenderId;
  17624. }
  17625. };
  17626. /** @hidden */
  17627. Node.prototype.isSynchronizedWithParent = function () {
  17628. if (!this.parent) {
  17629. return true;
  17630. }
  17631. if (this._parentRenderId !== this.parent._childRenderId) {
  17632. return false;
  17633. }
  17634. return this.parent.isSynchronized();
  17635. };
  17636. /** @hidden */
  17637. Node.prototype.isSynchronized = function (updateCache) {
  17638. var check = this.hasNewParent();
  17639. check = check || !this.isSynchronizedWithParent();
  17640. check = check || !this._isSynchronized();
  17641. if (updateCache)
  17642. this.updateCache(true);
  17643. return !check;
  17644. };
  17645. /** @hidden */
  17646. Node.prototype.hasNewParent = function (update) {
  17647. if (this._cache.parent === this.parent)
  17648. return false;
  17649. if (update)
  17650. this._cache.parent = this.parent;
  17651. return true;
  17652. };
  17653. /**
  17654. * Is this node ready to be used/rendered
  17655. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17656. * @return true if the node is ready
  17657. */
  17658. Node.prototype.isReady = function (completeCheck) {
  17659. if (completeCheck === void 0) { completeCheck = false; }
  17660. return this._isReady;
  17661. };
  17662. /**
  17663. * Is this node enabled?
  17664. * 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
  17665. * @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
  17666. * @return whether this node (and its parent) is enabled
  17667. */
  17668. Node.prototype.isEnabled = function (checkAncestors) {
  17669. if (checkAncestors === void 0) { checkAncestors = true; }
  17670. if (checkAncestors === false) {
  17671. return this._isEnabled;
  17672. }
  17673. if (this._isEnabled === false) {
  17674. return false;
  17675. }
  17676. if (this.parent !== undefined && this.parent !== null) {
  17677. return this.parent.isEnabled(checkAncestors);
  17678. }
  17679. return true;
  17680. };
  17681. /**
  17682. * Set the enabled state of this node
  17683. * @param value defines the new enabled state
  17684. */
  17685. Node.prototype.setEnabled = function (value) {
  17686. this._isEnabled = value;
  17687. };
  17688. /**
  17689. * Is this node a descendant of the given node?
  17690. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17691. * @param ancestor defines the parent node to inspect
  17692. * @returns a boolean indicating if this node is a descendant of the given node
  17693. */
  17694. Node.prototype.isDescendantOf = function (ancestor) {
  17695. if (this.parent) {
  17696. if (this.parent === ancestor) {
  17697. return true;
  17698. }
  17699. return this.parent.isDescendantOf(ancestor);
  17700. }
  17701. return false;
  17702. };
  17703. /** @hidden */
  17704. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17705. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17706. if (!this._children) {
  17707. return;
  17708. }
  17709. for (var index = 0; index < this._children.length; index++) {
  17710. var item = this._children[index];
  17711. if (!predicate || predicate(item)) {
  17712. results.push(item);
  17713. }
  17714. if (!directDescendantsOnly) {
  17715. item._getDescendants(results, false, predicate);
  17716. }
  17717. }
  17718. };
  17719. /**
  17720. * Will return all nodes that have this node as ascendant
  17721. * @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
  17722. * @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
  17723. * @return all children nodes of all types
  17724. */
  17725. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17726. var results = new Array();
  17727. this._getDescendants(results, directDescendantsOnly, predicate);
  17728. return results;
  17729. };
  17730. /**
  17731. * Get all child-meshes of this node
  17732. * @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
  17733. * @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
  17734. * @returns an array of {BABYLON.AbstractMesh}
  17735. */
  17736. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17737. var results = [];
  17738. this._getDescendants(results, directDescendantsOnly, function (node) {
  17739. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17740. });
  17741. return results;
  17742. };
  17743. /**
  17744. * Get all child-transformNodes of this node
  17745. * @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
  17746. * @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
  17747. * @returns an array of {BABYLON.TransformNode}
  17748. */
  17749. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17750. var results = [];
  17751. this._getDescendants(results, directDescendantsOnly, function (node) {
  17752. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17753. });
  17754. return results;
  17755. };
  17756. /**
  17757. * Get all direct children of this node
  17758. * @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
  17759. * @returns an array of {BABYLON.Node}
  17760. */
  17761. Node.prototype.getChildren = function (predicate) {
  17762. return this.getDescendants(true, predicate);
  17763. };
  17764. /** @hidden */
  17765. Node.prototype._setReady = function (state) {
  17766. if (state === this._isReady) {
  17767. return;
  17768. }
  17769. if (!state) {
  17770. this._isReady = false;
  17771. return;
  17772. }
  17773. if (this.onReady) {
  17774. this.onReady(this);
  17775. }
  17776. this._isReady = true;
  17777. };
  17778. /**
  17779. * Get an animation by name
  17780. * @param name defines the name of the animation to look for
  17781. * @returns null if not found else the requested animation
  17782. */
  17783. Node.prototype.getAnimationByName = function (name) {
  17784. for (var i = 0; i < this.animations.length; i++) {
  17785. var animation = this.animations[i];
  17786. if (animation.name === name) {
  17787. return animation;
  17788. }
  17789. }
  17790. return null;
  17791. };
  17792. /**
  17793. * Creates an animation range for this node
  17794. * @param name defines the name of the range
  17795. * @param from defines the starting key
  17796. * @param to defines the end key
  17797. */
  17798. Node.prototype.createAnimationRange = function (name, from, to) {
  17799. // check name not already in use
  17800. if (!this._ranges[name]) {
  17801. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17802. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17803. if (this.animations[i]) {
  17804. this.animations[i].createRange(name, from, to);
  17805. }
  17806. }
  17807. }
  17808. };
  17809. /**
  17810. * Delete a specific animation range
  17811. * @param name defines the name of the range to delete
  17812. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17813. */
  17814. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17815. if (deleteFrames === void 0) { deleteFrames = true; }
  17816. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17817. if (this.animations[i]) {
  17818. this.animations[i].deleteRange(name, deleteFrames);
  17819. }
  17820. }
  17821. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17822. };
  17823. /**
  17824. * Get an animation range by name
  17825. * @param name defines the name of the animation range to look for
  17826. * @returns null if not found else the requested animation range
  17827. */
  17828. Node.prototype.getAnimationRange = function (name) {
  17829. return this._ranges[name];
  17830. };
  17831. /**
  17832. * Will start the animation sequence
  17833. * @param name defines the range frames for animation sequence
  17834. * @param loop defines if the animation should loop (false by default)
  17835. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17836. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17837. * @returns the object created for this animation. If range does not exist, it will return null
  17838. */
  17839. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17840. var range = this.getAnimationRange(name);
  17841. if (!range) {
  17842. return null;
  17843. }
  17844. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17845. };
  17846. /**
  17847. * Serialize animation ranges into a JSON compatible object
  17848. * @returns serialization object
  17849. */
  17850. Node.prototype.serializeAnimationRanges = function () {
  17851. var serializationRanges = [];
  17852. for (var name in this._ranges) {
  17853. var localRange = this._ranges[name];
  17854. if (!localRange) {
  17855. continue;
  17856. }
  17857. var range = {};
  17858. range.name = name;
  17859. range.from = localRange.from;
  17860. range.to = localRange.to;
  17861. serializationRanges.push(range);
  17862. }
  17863. return serializationRanges;
  17864. };
  17865. /**
  17866. * Computes the world matrix of the node
  17867. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17868. * @returns the world matrix
  17869. */
  17870. Node.prototype.computeWorldMatrix = function (force) {
  17871. return BABYLON.Matrix.Identity();
  17872. };
  17873. /**
  17874. * Releases resources associated with this node.
  17875. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17876. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17877. */
  17878. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17879. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17880. if (!doNotRecurse) {
  17881. var nodes = this.getDescendants(true);
  17882. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17883. var node = nodes_1[_i];
  17884. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17885. }
  17886. }
  17887. else {
  17888. var transformNodes = this.getChildTransformNodes(true);
  17889. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17890. var transformNode = transformNodes_1[_a];
  17891. transformNode.parent = null;
  17892. transformNode.computeWorldMatrix(true);
  17893. }
  17894. }
  17895. this.parent = null;
  17896. // Callback
  17897. this.onDisposeObservable.notifyObservers(this);
  17898. this.onDisposeObservable.clear();
  17899. // Behaviors
  17900. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17901. var behavior = _c[_b];
  17902. behavior.detach();
  17903. }
  17904. this._behaviors = [];
  17905. this._isDisposed = true;
  17906. };
  17907. /**
  17908. * Parse animation range data from a serialization object and store them into a given node
  17909. * @param node defines where to store the animation ranges
  17910. * @param parsedNode defines the serialization object to read data from
  17911. * @param scene defines the hosting scene
  17912. */
  17913. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17914. if (parsedNode.ranges) {
  17915. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17916. var data = parsedNode.ranges[index];
  17917. node.createAnimationRange(data.name, data.from, data.to);
  17918. }
  17919. }
  17920. };
  17921. __decorate([
  17922. BABYLON.serialize()
  17923. ], Node.prototype, "name", void 0);
  17924. __decorate([
  17925. BABYLON.serialize()
  17926. ], Node.prototype, "id", void 0);
  17927. __decorate([
  17928. BABYLON.serialize()
  17929. ], Node.prototype, "uniqueId", void 0);
  17930. __decorate([
  17931. BABYLON.serialize()
  17932. ], Node.prototype, "state", void 0);
  17933. __decorate([
  17934. BABYLON.serialize()
  17935. ], Node.prototype, "metadata", void 0);
  17936. return Node;
  17937. }());
  17938. BABYLON.Node = Node;
  17939. })(BABYLON || (BABYLON = {}));
  17940. //# sourceMappingURL=babylon.node.js.map
  17941. var BABYLON;
  17942. (function (BABYLON) {
  17943. var BoundingSphere = /** @class */ (function () {
  17944. /**
  17945. * Creates a new bounding sphere
  17946. * @param min defines the minimum vector (in local space)
  17947. * @param max defines the maximum vector (in local space)
  17948. */
  17949. function BoundingSphere(min, max) {
  17950. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17951. this.reConstruct(min, max);
  17952. }
  17953. /**
  17954. * Recreates the entire bounding sphere from scratch
  17955. * @param min defines the new minimum vector (in local space)
  17956. * @param max defines the new maximum vector (in local space)
  17957. */
  17958. BoundingSphere.prototype.reConstruct = function (min, max) {
  17959. this.minimum = min.clone();
  17960. this.maximum = max.clone();
  17961. var distance = BABYLON.Vector3.Distance(min, max);
  17962. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17963. this.radius = distance * 0.5;
  17964. this.centerWorld = BABYLON.Vector3.Zero();
  17965. this._update(BABYLON.Matrix.Identity());
  17966. };
  17967. // Methods
  17968. BoundingSphere.prototype._update = function (world) {
  17969. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17970. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17971. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17972. };
  17973. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17974. for (var i = 0; i < 6; i++) {
  17975. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17976. return false;
  17977. }
  17978. return true;
  17979. };
  17980. BoundingSphere.prototype.intersectsPoint = function (point) {
  17981. var x = this.centerWorld.x - point.x;
  17982. var y = this.centerWorld.y - point.y;
  17983. var z = this.centerWorld.z - point.z;
  17984. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17985. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17986. return false;
  17987. return true;
  17988. };
  17989. // Statics
  17990. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17991. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17992. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17993. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17994. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17995. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17996. return false;
  17997. return true;
  17998. };
  17999. return BoundingSphere;
  18000. }());
  18001. BABYLON.BoundingSphere = BoundingSphere;
  18002. })(BABYLON || (BABYLON = {}));
  18003. //# sourceMappingURL=babylon.boundingSphere.js.map
  18004. var BABYLON;
  18005. (function (BABYLON) {
  18006. var BoundingBox = /** @class */ (function () {
  18007. /**
  18008. * Creates a new bounding box
  18009. * @param min defines the minimum vector (in local space)
  18010. * @param max defines the maximum vector (in local space)
  18011. */
  18012. function BoundingBox(min, max) {
  18013. this.vectorsWorld = new Array();
  18014. this.reConstruct(min, max);
  18015. }
  18016. // Methods
  18017. /**
  18018. * Recreates the entire bounding box from scratch
  18019. * @param min defines the new minimum vector (in local space)
  18020. * @param max defines the new maximum vector (in local space)
  18021. */
  18022. BoundingBox.prototype.reConstruct = function (min, max) {
  18023. this.minimum = min.clone();
  18024. this.maximum = max.clone();
  18025. // Bounding vectors
  18026. this.vectors = new Array();
  18027. this.vectors.push(this.minimum.clone());
  18028. this.vectors.push(this.maximum.clone());
  18029. this.vectors.push(this.minimum.clone());
  18030. this.vectors[2].x = this.maximum.x;
  18031. this.vectors.push(this.minimum.clone());
  18032. this.vectors[3].y = this.maximum.y;
  18033. this.vectors.push(this.minimum.clone());
  18034. this.vectors[4].z = this.maximum.z;
  18035. this.vectors.push(this.maximum.clone());
  18036. this.vectors[5].z = this.minimum.z;
  18037. this.vectors.push(this.maximum.clone());
  18038. this.vectors[6].x = this.minimum.x;
  18039. this.vectors.push(this.maximum.clone());
  18040. this.vectors[7].y = this.minimum.y;
  18041. // OBB
  18042. this.center = this.maximum.add(this.minimum).scale(0.5);
  18043. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18044. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18045. // World
  18046. for (var index = 0; index < this.vectors.length; index++) {
  18047. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18048. }
  18049. this.minimumWorld = BABYLON.Vector3.Zero();
  18050. this.maximumWorld = BABYLON.Vector3.Zero();
  18051. this.centerWorld = BABYLON.Vector3.Zero();
  18052. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18053. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18054. };
  18055. BoundingBox.prototype.getWorldMatrix = function () {
  18056. return this._worldMatrix;
  18057. };
  18058. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18059. this._worldMatrix.copyFrom(matrix);
  18060. return this;
  18061. };
  18062. BoundingBox.prototype._update = function (world) {
  18063. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18064. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18065. for (var index = 0; index < this.vectors.length; index++) {
  18066. var v = this.vectorsWorld[index];
  18067. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18068. if (v.x < this.minimumWorld.x)
  18069. this.minimumWorld.x = v.x;
  18070. if (v.y < this.minimumWorld.y)
  18071. this.minimumWorld.y = v.y;
  18072. if (v.z < this.minimumWorld.z)
  18073. this.minimumWorld.z = v.z;
  18074. if (v.x > this.maximumWorld.x)
  18075. this.maximumWorld.x = v.x;
  18076. if (v.y > this.maximumWorld.y)
  18077. this.maximumWorld.y = v.y;
  18078. if (v.z > this.maximumWorld.z)
  18079. this.maximumWorld.z = v.z;
  18080. }
  18081. // Extend
  18082. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18083. this.extendSizeWorld.scaleInPlace(0.5);
  18084. // OBB
  18085. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18086. this.centerWorld.scaleInPlace(0.5);
  18087. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18088. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18089. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18090. this._worldMatrix = world;
  18091. };
  18092. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18093. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18094. };
  18095. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18096. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18097. };
  18098. BoundingBox.prototype.intersectsPoint = function (point) {
  18099. var delta = -BABYLON.Epsilon;
  18100. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18101. return false;
  18102. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18103. return false;
  18104. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18105. return false;
  18106. return true;
  18107. };
  18108. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18109. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18110. };
  18111. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18112. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18113. return false;
  18114. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18115. return false;
  18116. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18117. return false;
  18118. return true;
  18119. };
  18120. // Statics
  18121. BoundingBox.Intersects = function (box0, box1) {
  18122. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18123. return false;
  18124. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18125. return false;
  18126. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18127. return false;
  18128. return true;
  18129. };
  18130. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18131. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18132. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18133. return (num <= (sphereRadius * sphereRadius));
  18134. };
  18135. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18136. for (var p = 0; p < 6; p++) {
  18137. for (var i = 0; i < 8; i++) {
  18138. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18139. return false;
  18140. }
  18141. }
  18142. }
  18143. return true;
  18144. };
  18145. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18146. for (var p = 0; p < 6; p++) {
  18147. var inCount = 8;
  18148. for (var i = 0; i < 8; i++) {
  18149. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18150. --inCount;
  18151. }
  18152. else {
  18153. break;
  18154. }
  18155. }
  18156. if (inCount === 0)
  18157. return false;
  18158. }
  18159. return true;
  18160. };
  18161. return BoundingBox;
  18162. }());
  18163. BABYLON.BoundingBox = BoundingBox;
  18164. })(BABYLON || (BABYLON = {}));
  18165. //# sourceMappingURL=babylon.boundingBox.js.map
  18166. var BABYLON;
  18167. (function (BABYLON) {
  18168. var computeBoxExtents = function (axis, box) {
  18169. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18170. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18171. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18172. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18173. var r = r0 + r1 + r2;
  18174. return {
  18175. min: p - r,
  18176. max: p + r
  18177. };
  18178. };
  18179. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18180. var axisOverlap = function (axis, box0, box1) {
  18181. var result0 = computeBoxExtents(axis, box0);
  18182. var result1 = computeBoxExtents(axis, box1);
  18183. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18184. };
  18185. var BoundingInfo = /** @class */ (function () {
  18186. function BoundingInfo(minimum, maximum) {
  18187. this.minimum = minimum;
  18188. this.maximum = maximum;
  18189. this._isLocked = false;
  18190. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18191. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18192. }
  18193. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18194. get: function () {
  18195. return this._isLocked;
  18196. },
  18197. set: function (value) {
  18198. this._isLocked = value;
  18199. },
  18200. enumerable: true,
  18201. configurable: true
  18202. });
  18203. // Methods
  18204. BoundingInfo.prototype.update = function (world) {
  18205. if (this._isLocked) {
  18206. return;
  18207. }
  18208. this.boundingBox._update(world);
  18209. this.boundingSphere._update(world);
  18210. };
  18211. /**
  18212. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18213. * @param center New center of the bounding info
  18214. * @param extend New extend of the bounding info
  18215. */
  18216. BoundingInfo.prototype.centerOn = function (center, extend) {
  18217. this.minimum = center.subtract(extend);
  18218. this.maximum = center.add(extend);
  18219. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18220. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18221. return this;
  18222. };
  18223. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18224. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18225. return false;
  18226. return this.boundingBox.isInFrustum(frustumPlanes);
  18227. };
  18228. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18229. /**
  18230. * Gets the world distance between the min and max points of the bounding box
  18231. */
  18232. get: function () {
  18233. var boundingBox = this.boundingBox;
  18234. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18235. return size.length();
  18236. },
  18237. enumerable: true,
  18238. configurable: true
  18239. });
  18240. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18241. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18242. };
  18243. BoundingInfo.prototype._checkCollision = function (collider) {
  18244. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18245. };
  18246. BoundingInfo.prototype.intersectsPoint = function (point) {
  18247. if (!this.boundingSphere.centerWorld) {
  18248. return false;
  18249. }
  18250. if (!this.boundingSphere.intersectsPoint(point)) {
  18251. return false;
  18252. }
  18253. if (!this.boundingBox.intersectsPoint(point)) {
  18254. return false;
  18255. }
  18256. return true;
  18257. };
  18258. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18259. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18260. return false;
  18261. }
  18262. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18263. return false;
  18264. }
  18265. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18266. return false;
  18267. }
  18268. if (!precise) {
  18269. return true;
  18270. }
  18271. var box0 = this.boundingBox;
  18272. var box1 = boundingInfo.boundingBox;
  18273. if (!axisOverlap(box0.directions[0], box0, box1))
  18274. return false;
  18275. if (!axisOverlap(box0.directions[1], box0, box1))
  18276. return false;
  18277. if (!axisOverlap(box0.directions[2], box0, box1))
  18278. return false;
  18279. if (!axisOverlap(box1.directions[0], box0, box1))
  18280. return false;
  18281. if (!axisOverlap(box1.directions[1], box0, box1))
  18282. return false;
  18283. if (!axisOverlap(box1.directions[2], box0, box1))
  18284. return false;
  18285. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18286. return false;
  18287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18288. return false;
  18289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18290. return false;
  18291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18292. return false;
  18293. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18294. return false;
  18295. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18296. return false;
  18297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18298. return false;
  18299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18300. return false;
  18301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18302. return false;
  18303. return true;
  18304. };
  18305. return BoundingInfo;
  18306. }());
  18307. BABYLON.BoundingInfo = BoundingInfo;
  18308. })(BABYLON || (BABYLON = {}));
  18309. //# sourceMappingURL=babylon.boundingInfo.js.map
  18310. var BABYLON;
  18311. (function (BABYLON) {
  18312. var TransformNode = /** @class */ (function (_super) {
  18313. __extends(TransformNode, _super);
  18314. function TransformNode(name, scene, isPure) {
  18315. if (scene === void 0) { scene = null; }
  18316. if (isPure === void 0) { isPure = true; }
  18317. var _this = _super.call(this, name, scene) || this;
  18318. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18319. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18320. _this._up = new BABYLON.Vector3(0, 1, 0);
  18321. _this._right = new BABYLON.Vector3(1, 0, 0);
  18322. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18323. // Properties
  18324. _this._rotation = BABYLON.Vector3.Zero();
  18325. _this._scaling = BABYLON.Vector3.One();
  18326. _this._isDirty = false;
  18327. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18328. _this.scalingDeterminant = 1;
  18329. _this.infiniteDistance = false;
  18330. _this.position = BABYLON.Vector3.Zero();
  18331. _this._localWorld = BABYLON.Matrix.Zero();
  18332. _this._worldMatrix = BABYLON.Matrix.Zero();
  18333. _this._worldMatrixDeterminant = 0;
  18334. _this._absolutePosition = BABYLON.Vector3.Zero();
  18335. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18336. _this._postMultiplyPivotMatrix = false;
  18337. _this._isWorldMatrixFrozen = false;
  18338. /**
  18339. * An event triggered after the world matrix is updated
  18340. */
  18341. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18342. _this._nonUniformScaling = false;
  18343. if (isPure) {
  18344. _this.getScene().addTransformNode(_this);
  18345. }
  18346. return _this;
  18347. }
  18348. /**
  18349. * Gets a string idenfifying the name of the class
  18350. * @returns "TransformNode" string
  18351. */
  18352. TransformNode.prototype.getClassName = function () {
  18353. return "TransformNode";
  18354. };
  18355. Object.defineProperty(TransformNode.prototype, "rotation", {
  18356. /**
  18357. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18358. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18359. * Default : (0.0, 0.0, 0.0)
  18360. */
  18361. get: function () {
  18362. return this._rotation;
  18363. },
  18364. set: function (newRotation) {
  18365. this._rotation = newRotation;
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(TransformNode.prototype, "scaling", {
  18371. /**
  18372. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18373. * Default : (1.0, 1.0, 1.0)
  18374. */
  18375. get: function () {
  18376. return this._scaling;
  18377. },
  18378. /**
  18379. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18380. * Default : (1.0, 1.0, 1.0)
  18381. */
  18382. set: function (newScaling) {
  18383. this._scaling = newScaling;
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18389. /**
  18390. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18391. * It's null by default.
  18392. * 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)
  18393. */
  18394. get: function () {
  18395. return this._rotationQuaternion;
  18396. },
  18397. set: function (quaternion) {
  18398. this._rotationQuaternion = quaternion;
  18399. //reset the rotation vector.
  18400. if (quaternion && this.rotation.length()) {
  18401. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18402. }
  18403. },
  18404. enumerable: true,
  18405. configurable: true
  18406. });
  18407. Object.defineProperty(TransformNode.prototype, "forward", {
  18408. /**
  18409. * The forward direction of that transform in world space.
  18410. */
  18411. get: function () {
  18412. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(TransformNode.prototype, "up", {
  18418. /**
  18419. * The up direction of that transform in world space.
  18420. */
  18421. get: function () {
  18422. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. Object.defineProperty(TransformNode.prototype, "right", {
  18428. /**
  18429. * The right direction of that transform in world space.
  18430. */
  18431. get: function () {
  18432. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18433. },
  18434. enumerable: true,
  18435. configurable: true
  18436. });
  18437. /**
  18438. * Returns the latest update of the World matrix
  18439. * Returns a Matrix.
  18440. */
  18441. TransformNode.prototype.getWorldMatrix = function () {
  18442. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18443. this.computeWorldMatrix();
  18444. }
  18445. return this._worldMatrix;
  18446. };
  18447. /** @hidden */
  18448. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18449. return this._worldMatrixDeterminant;
  18450. };
  18451. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18452. /**
  18453. * Returns directly the latest state of the mesh World matrix.
  18454. * A Matrix is returned.
  18455. */
  18456. get: function () {
  18457. return this._worldMatrix;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. /**
  18463. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18464. * Returns the TransformNode.
  18465. */
  18466. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18467. this._poseMatrix.copyFrom(matrix);
  18468. return this;
  18469. };
  18470. /**
  18471. * Returns the mesh Pose matrix.
  18472. * Returned object : Matrix
  18473. */
  18474. TransformNode.prototype.getPoseMatrix = function () {
  18475. return this._poseMatrix;
  18476. };
  18477. TransformNode.prototype._isSynchronized = function () {
  18478. if (this._isDirty) {
  18479. return false;
  18480. }
  18481. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18482. return false;
  18483. if (this._cache.pivotMatrixUpdated) {
  18484. return false;
  18485. }
  18486. if (this.infiniteDistance) {
  18487. return false;
  18488. }
  18489. if (!this._cache.position.equals(this.position))
  18490. return false;
  18491. if (this.rotationQuaternion) {
  18492. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18493. return false;
  18494. }
  18495. if (!this._cache.rotation.equals(this.rotation))
  18496. return false;
  18497. if (!this._cache.scaling.equals(this.scaling))
  18498. return false;
  18499. return true;
  18500. };
  18501. TransformNode.prototype._initCache = function () {
  18502. _super.prototype._initCache.call(this);
  18503. this._cache.localMatrixUpdated = false;
  18504. this._cache.position = BABYLON.Vector3.Zero();
  18505. this._cache.scaling = BABYLON.Vector3.Zero();
  18506. this._cache.rotation = BABYLON.Vector3.Zero();
  18507. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18508. this._cache.billboardMode = -1;
  18509. };
  18510. TransformNode.prototype.markAsDirty = function (property) {
  18511. if (property === "rotation") {
  18512. this.rotationQuaternion = null;
  18513. }
  18514. this._currentRenderId = Number.MAX_VALUE;
  18515. this._isDirty = true;
  18516. return this;
  18517. };
  18518. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18519. /**
  18520. * Returns the current mesh absolute position.
  18521. * Retuns a Vector3.
  18522. */
  18523. get: function () {
  18524. return this._absolutePosition;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. /**
  18530. * Sets a new matrix to apply before all other transformation
  18531. * @param matrix defines the transform matrix
  18532. * @returns the current TransformNode
  18533. */
  18534. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18535. return this.setPivotMatrix(matrix, false);
  18536. };
  18537. /**
  18538. * Sets a new pivot matrix to the current node
  18539. * @param matrix defines the new pivot matrix to use
  18540. * @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
  18541. * @returns the current TransformNode
  18542. */
  18543. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18544. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18545. this._pivotMatrix = matrix.clone();
  18546. this._cache.pivotMatrixUpdated = true;
  18547. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18548. if (this._postMultiplyPivotMatrix) {
  18549. if (!this._pivotMatrixInverse) {
  18550. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18551. }
  18552. else {
  18553. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18554. }
  18555. }
  18556. return this;
  18557. };
  18558. /**
  18559. * Returns the mesh pivot matrix.
  18560. * Default : Identity.
  18561. * A Matrix is returned.
  18562. */
  18563. TransformNode.prototype.getPivotMatrix = function () {
  18564. return this._pivotMatrix;
  18565. };
  18566. /**
  18567. * Prevents the World matrix to be computed any longer.
  18568. * Returns the TransformNode.
  18569. */
  18570. TransformNode.prototype.freezeWorldMatrix = function () {
  18571. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18572. this.computeWorldMatrix(true);
  18573. this._isWorldMatrixFrozen = true;
  18574. return this;
  18575. };
  18576. /**
  18577. * Allows back the World matrix computation.
  18578. * Returns the TransformNode.
  18579. */
  18580. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18581. this._isWorldMatrixFrozen = false;
  18582. this.computeWorldMatrix(true);
  18583. return this;
  18584. };
  18585. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18586. /**
  18587. * True if the World matrix has been frozen.
  18588. * Returns a boolean.
  18589. */
  18590. get: function () {
  18591. return this._isWorldMatrixFrozen;
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. /**
  18597. * Retuns the mesh absolute position in the World.
  18598. * Returns a Vector3.
  18599. */
  18600. TransformNode.prototype.getAbsolutePosition = function () {
  18601. this.computeWorldMatrix();
  18602. return this._absolutePosition;
  18603. };
  18604. /**
  18605. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18606. * Returns the TransformNode.
  18607. */
  18608. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18609. if (!absolutePosition) {
  18610. return this;
  18611. }
  18612. var absolutePositionX;
  18613. var absolutePositionY;
  18614. var absolutePositionZ;
  18615. if (absolutePosition.x === undefined) {
  18616. if (arguments.length < 3) {
  18617. return this;
  18618. }
  18619. absolutePositionX = arguments[0];
  18620. absolutePositionY = arguments[1];
  18621. absolutePositionZ = arguments[2];
  18622. }
  18623. else {
  18624. absolutePositionX = absolutePosition.x;
  18625. absolutePositionY = absolutePosition.y;
  18626. absolutePositionZ = absolutePosition.z;
  18627. }
  18628. if (this.parent) {
  18629. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18630. invertParentWorldMatrix.invert();
  18631. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18632. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18633. }
  18634. else {
  18635. this.position.x = absolutePositionX;
  18636. this.position.y = absolutePositionY;
  18637. this.position.z = absolutePositionZ;
  18638. }
  18639. return this;
  18640. };
  18641. /**
  18642. * Sets the mesh position in its local space.
  18643. * Returns the TransformNode.
  18644. */
  18645. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18646. this.computeWorldMatrix();
  18647. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18648. return this;
  18649. };
  18650. /**
  18651. * Returns the mesh position in the local space from the current World matrix values.
  18652. * Returns a new Vector3.
  18653. */
  18654. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18655. this.computeWorldMatrix();
  18656. var invLocalWorldMatrix = this._localWorld.clone();
  18657. invLocalWorldMatrix.invert();
  18658. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18659. };
  18660. /**
  18661. * Translates the mesh along the passed Vector3 in its local space.
  18662. * Returns the TransformNode.
  18663. */
  18664. TransformNode.prototype.locallyTranslate = function (vector3) {
  18665. this.computeWorldMatrix(true);
  18666. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18667. return this;
  18668. };
  18669. /**
  18670. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18671. * @param targetPoint the position (must be in same space as current mesh) to look at
  18672. * @param yawCor optional yaw (y-axis) correction in radians
  18673. * @param pitchCor optional pitch (x-axis) correction in radians
  18674. * @param rollCor optional roll (z-axis) correction in radians
  18675. * @param space the choosen space of the target
  18676. * @returns the TransformNode.
  18677. */
  18678. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18679. if (yawCor === void 0) { yawCor = 0; }
  18680. if (pitchCor === void 0) { pitchCor = 0; }
  18681. if (rollCor === void 0) { rollCor = 0; }
  18682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18683. var dv = TransformNode._lookAtVectorCache;
  18684. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18685. targetPoint.subtractToRef(pos, dv);
  18686. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18687. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18688. var pitch = Math.atan2(dv.y, len);
  18689. if (this.rotationQuaternion) {
  18690. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18691. }
  18692. else {
  18693. this.rotation.x = pitch + pitchCor;
  18694. this.rotation.y = yaw + yawCor;
  18695. this.rotation.z = rollCor;
  18696. }
  18697. return this;
  18698. };
  18699. /**
  18700. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18701. * This Vector3 is expressed in the World space.
  18702. */
  18703. TransformNode.prototype.getDirection = function (localAxis) {
  18704. var result = BABYLON.Vector3.Zero();
  18705. this.getDirectionToRef(localAxis, result);
  18706. return result;
  18707. };
  18708. /**
  18709. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18710. * localAxis is expressed in the mesh local space.
  18711. * result is computed in the Wordl space from the mesh World matrix.
  18712. * Returns the TransformNode.
  18713. */
  18714. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18715. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18716. return this;
  18717. };
  18718. /**
  18719. * Sets a new pivot point to the current node
  18720. * @param point defines the new pivot point to use
  18721. * @param space defines if the point is in world or local space (local by default)
  18722. * @returns the current TransformNode
  18723. */
  18724. TransformNode.prototype.setPivotPoint = function (point, space) {
  18725. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18726. if (this.getScene().getRenderId() == 0) {
  18727. this.computeWorldMatrix(true);
  18728. }
  18729. var wm = this.getWorldMatrix();
  18730. if (space == BABYLON.Space.WORLD) {
  18731. var tmat = BABYLON.Tmp.Matrix[0];
  18732. wm.invertToRef(tmat);
  18733. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18734. }
  18735. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18736. };
  18737. /**
  18738. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18739. */
  18740. TransformNode.prototype.getPivotPoint = function () {
  18741. var point = BABYLON.Vector3.Zero();
  18742. this.getPivotPointToRef(point);
  18743. return point;
  18744. };
  18745. /**
  18746. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18747. * Returns the TransformNode.
  18748. */
  18749. TransformNode.prototype.getPivotPointToRef = function (result) {
  18750. result.x = -this._pivotMatrix.m[12];
  18751. result.y = -this._pivotMatrix.m[13];
  18752. result.z = -this._pivotMatrix.m[14];
  18753. return this;
  18754. };
  18755. /**
  18756. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18757. */
  18758. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18759. var point = BABYLON.Vector3.Zero();
  18760. this.getAbsolutePivotPointToRef(point);
  18761. return point;
  18762. };
  18763. /**
  18764. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18765. * Returns the TransformNode.
  18766. */
  18767. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18768. result.x = this._pivotMatrix.m[12];
  18769. result.y = this._pivotMatrix.m[13];
  18770. result.z = this._pivotMatrix.m[14];
  18771. this.getPivotPointToRef(result);
  18772. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18773. return this;
  18774. };
  18775. /**
  18776. * Defines the passed node as the parent of the current node.
  18777. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18778. * Returns the TransformNode.
  18779. */
  18780. TransformNode.prototype.setParent = function (node) {
  18781. if (node === null) {
  18782. var rotation = BABYLON.Tmp.Quaternion[0];
  18783. var position = BABYLON.Tmp.Vector3[0];
  18784. var scale = BABYLON.Tmp.Vector3[1];
  18785. if (this.parent && this.parent.computeWorldMatrix) {
  18786. this.parent.computeWorldMatrix(true);
  18787. }
  18788. this.computeWorldMatrix(true);
  18789. this.getWorldMatrix().decompose(scale, rotation, position);
  18790. if (this.rotationQuaternion) {
  18791. this.rotationQuaternion.copyFrom(rotation);
  18792. }
  18793. else {
  18794. rotation.toEulerAnglesToRef(this.rotation);
  18795. }
  18796. this.scaling.x = scale.x;
  18797. this.scaling.y = scale.y;
  18798. this.scaling.z = scale.z;
  18799. this.position.x = position.x;
  18800. this.position.y = position.y;
  18801. this.position.z = position.z;
  18802. }
  18803. else {
  18804. var rotation = BABYLON.Tmp.Quaternion[0];
  18805. var position = BABYLON.Tmp.Vector3[0];
  18806. var scale = BABYLON.Tmp.Vector3[1];
  18807. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18808. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18809. this.computeWorldMatrix(true);
  18810. node.computeWorldMatrix(true);
  18811. node.getWorldMatrix().invertToRef(invParentMatrix);
  18812. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18813. diffMatrix.decompose(scale, rotation, position);
  18814. if (this.rotationQuaternion) {
  18815. this.rotationQuaternion.copyFrom(rotation);
  18816. }
  18817. else {
  18818. rotation.toEulerAnglesToRef(this.rotation);
  18819. }
  18820. this.position.x = position.x;
  18821. this.position.y = position.y;
  18822. this.position.z = position.z;
  18823. this.scaling.x = scale.x;
  18824. this.scaling.y = scale.y;
  18825. this.scaling.z = scale.z;
  18826. }
  18827. this.parent = node;
  18828. return this;
  18829. };
  18830. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18831. get: function () {
  18832. return this._nonUniformScaling;
  18833. },
  18834. enumerable: true,
  18835. configurable: true
  18836. });
  18837. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18838. if (this._nonUniformScaling === value) {
  18839. return false;
  18840. }
  18841. this._nonUniformScaling = true;
  18842. return true;
  18843. };
  18844. /**
  18845. * Attach the current TransformNode to another TransformNode associated with a bone
  18846. * @param bone Bone affecting the TransformNode
  18847. * @param affectedTransformNode TransformNode associated with the bone
  18848. */
  18849. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18850. this._transformToBoneReferal = affectedTransformNode;
  18851. this.parent = bone;
  18852. if (bone.getWorldMatrix().determinant() < 0) {
  18853. this.scalingDeterminant *= -1;
  18854. }
  18855. return this;
  18856. };
  18857. TransformNode.prototype.detachFromBone = function () {
  18858. if (!this.parent) {
  18859. return this;
  18860. }
  18861. if (this.parent.getWorldMatrix().determinant() < 0) {
  18862. this.scalingDeterminant *= -1;
  18863. }
  18864. this._transformToBoneReferal = null;
  18865. this.parent = null;
  18866. return this;
  18867. };
  18868. /**
  18869. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18870. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18871. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18872. * The passed axis is also normalized.
  18873. * Returns the TransformNode.
  18874. */
  18875. TransformNode.prototype.rotate = function (axis, amount, space) {
  18876. axis.normalize();
  18877. if (!this.rotationQuaternion) {
  18878. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18879. this.rotation = BABYLON.Vector3.Zero();
  18880. }
  18881. var rotationQuaternion;
  18882. if (!space || space === BABYLON.Space.LOCAL) {
  18883. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18884. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18885. }
  18886. else {
  18887. if (this.parent) {
  18888. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18889. invertParentWorldMatrix.invert();
  18890. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18891. }
  18892. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18893. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18894. }
  18895. return this;
  18896. };
  18897. /**
  18898. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18899. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18900. * The passed axis is also normalized.
  18901. * Returns the TransformNode.
  18902. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18903. */
  18904. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18905. axis.normalize();
  18906. if (!this.rotationQuaternion) {
  18907. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18908. this.rotation.copyFromFloats(0, 0, 0);
  18909. }
  18910. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18911. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18912. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18913. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18914. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18915. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18916. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18917. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18918. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18919. return this;
  18920. };
  18921. /**
  18922. * Translates the mesh along the axis vector for the passed distance in the given space.
  18923. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18924. * Returns the TransformNode.
  18925. */
  18926. TransformNode.prototype.translate = function (axis, distance, space) {
  18927. var displacementVector = axis.scale(distance);
  18928. if (!space || space === BABYLON.Space.LOCAL) {
  18929. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18930. this.setPositionWithLocalVector(tempV3);
  18931. }
  18932. else {
  18933. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18934. }
  18935. return this;
  18936. };
  18937. /**
  18938. * Adds a rotation step to the mesh current rotation.
  18939. * x, y, z are Euler angles expressed in radians.
  18940. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18941. * This means this rotation is made in the mesh local space only.
  18942. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18943. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18944. * ```javascript
  18945. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18946. * ```
  18947. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18948. * 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.
  18949. * Returns the TransformNode.
  18950. */
  18951. TransformNode.prototype.addRotation = function (x, y, z) {
  18952. var rotationQuaternion;
  18953. if (this.rotationQuaternion) {
  18954. rotationQuaternion = this.rotationQuaternion;
  18955. }
  18956. else {
  18957. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18958. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18959. }
  18960. var accumulation = BABYLON.Tmp.Quaternion[0];
  18961. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18962. rotationQuaternion.multiplyInPlace(accumulation);
  18963. if (!this.rotationQuaternion) {
  18964. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18965. }
  18966. return this;
  18967. };
  18968. /**
  18969. * Computes the mesh World matrix and returns it.
  18970. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18971. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18972. * If the parameter `force`is set to `true`, the actual computation is done.
  18973. * Returns the mesh World Matrix.
  18974. */
  18975. TransformNode.prototype.computeWorldMatrix = function (force) {
  18976. if (this._isWorldMatrixFrozen) {
  18977. return this._worldMatrix;
  18978. }
  18979. if (!force && this.isSynchronized(true)) {
  18980. this._currentRenderId = this.getScene().getRenderId();
  18981. return this._worldMatrix;
  18982. }
  18983. this._cache.position.copyFrom(this.position);
  18984. this._cache.scaling.copyFrom(this.scaling);
  18985. this._cache.pivotMatrixUpdated = false;
  18986. this._cache.billboardMode = this.billboardMode;
  18987. this._currentRenderId = this.getScene().getRenderId();
  18988. this._childRenderId = this.getScene().getRenderId();
  18989. this._isDirty = false;
  18990. // Scaling
  18991. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18992. // Rotation
  18993. //rotate, if quaternion is set and rotation was used
  18994. if (this.rotationQuaternion) {
  18995. var len = this.rotation.length();
  18996. if (len) {
  18997. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18998. this.rotation.copyFromFloats(0, 0, 0);
  18999. }
  19000. }
  19001. if (this.rotationQuaternion) {
  19002. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19003. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19004. }
  19005. else {
  19006. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19007. this._cache.rotation.copyFrom(this.rotation);
  19008. }
  19009. // Translation
  19010. var camera = this.getScene().activeCamera;
  19011. if (this.infiniteDistance && !this.parent && camera) {
  19012. var cameraWorldMatrix = camera.getWorldMatrix();
  19013. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19014. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19015. }
  19016. else {
  19017. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19018. }
  19019. // Composing transformations
  19020. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19021. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19022. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19023. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19024. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19025. // Need to decompose each rotation here
  19026. var currentPosition = BABYLON.Tmp.Vector3[3];
  19027. if (this.parent && this.parent.getWorldMatrix) {
  19028. if (this._transformToBoneReferal) {
  19029. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19030. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19031. }
  19032. else {
  19033. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19034. }
  19035. }
  19036. else {
  19037. currentPosition.copyFrom(this.position);
  19038. }
  19039. currentPosition.subtractInPlace(camera.globalPosition);
  19040. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19041. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19042. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19043. }
  19044. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19045. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19046. }
  19047. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19048. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19049. }
  19050. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19051. }
  19052. else {
  19053. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19054. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19055. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19056. }
  19057. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19058. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19059. }
  19060. // Local world
  19061. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19062. // Parent
  19063. if (this.parent && this.parent.getWorldMatrix) {
  19064. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19065. if (this._transformToBoneReferal) {
  19066. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19067. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19068. }
  19069. else {
  19070. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19071. }
  19072. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19073. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19074. this._worldMatrix.copyFrom(this._localWorld);
  19075. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19076. }
  19077. else {
  19078. if (this._transformToBoneReferal) {
  19079. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19080. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19081. }
  19082. else {
  19083. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19084. }
  19085. }
  19086. this._markSyncedWithParent();
  19087. }
  19088. else {
  19089. this._worldMatrix.copyFrom(this._localWorld);
  19090. }
  19091. // Post multiply inverse of pivotMatrix
  19092. if (this._postMultiplyPivotMatrix) {
  19093. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19094. }
  19095. // Normal matrix
  19096. if (this.scaling.isNonUniform) {
  19097. this._updateNonUniformScalingState(true);
  19098. }
  19099. else if (this.parent && this.parent._nonUniformScaling) {
  19100. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19101. }
  19102. else {
  19103. this._updateNonUniformScalingState(false);
  19104. }
  19105. this._afterComputeWorldMatrix();
  19106. // Absolute position
  19107. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19108. // Callbacks
  19109. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19110. if (!this._poseMatrix) {
  19111. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19112. }
  19113. // Cache the determinant
  19114. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19115. return this._worldMatrix;
  19116. };
  19117. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19118. };
  19119. /**
  19120. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19121. * @param func: callback function to add
  19122. *
  19123. * Returns the TransformNode.
  19124. */
  19125. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19126. this.onAfterWorldMatrixUpdateObservable.add(func);
  19127. return this;
  19128. };
  19129. /**
  19130. * Removes a registered callback function.
  19131. * Returns the TransformNode.
  19132. */
  19133. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19134. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19135. return this;
  19136. };
  19137. /**
  19138. * Clone the current transform node
  19139. * Returns the new transform node
  19140. * @param name Name of the new clone
  19141. * @param newParent New parent for the clone
  19142. * @param doNotCloneChildren Do not clone children hierarchy
  19143. */
  19144. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19145. var _this = this;
  19146. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19147. result.name = name;
  19148. result.id = name;
  19149. if (newParent) {
  19150. result.parent = newParent;
  19151. }
  19152. if (!doNotCloneChildren) {
  19153. // Children
  19154. var directDescendants = this.getDescendants(true);
  19155. for (var index = 0; index < directDescendants.length; index++) {
  19156. var child = directDescendants[index];
  19157. if (child.clone) {
  19158. child.clone(name + "." + child.name, result);
  19159. }
  19160. }
  19161. }
  19162. return result;
  19163. };
  19164. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19165. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19166. serializationObject.type = this.getClassName();
  19167. // Parent
  19168. if (this.parent) {
  19169. serializationObject.parentId = this.parent.id;
  19170. }
  19171. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19172. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19173. }
  19174. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19175. serializationObject.isEnabled = this.isEnabled();
  19176. // Parent
  19177. if (this.parent) {
  19178. serializationObject.parentId = this.parent.id;
  19179. }
  19180. return serializationObject;
  19181. };
  19182. // Statics
  19183. /**
  19184. * Returns a new TransformNode object parsed from the source provided.
  19185. * The parameter `parsedMesh` is the source.
  19186. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19187. */
  19188. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19189. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19190. if (BABYLON.Tags) {
  19191. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19192. }
  19193. if (parsedTransformNode.localMatrix) {
  19194. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19195. }
  19196. else if (parsedTransformNode.pivotMatrix) {
  19197. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19198. }
  19199. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19200. // Parent
  19201. if (parsedTransformNode.parentId) {
  19202. transformNode._waitingParentId = parsedTransformNode.parentId;
  19203. }
  19204. return transformNode;
  19205. };
  19206. /**
  19207. * Releases resources associated with this transform node.
  19208. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19209. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19210. */
  19211. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19212. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19213. // Animations
  19214. this.getScene().stopAnimation(this);
  19215. // Remove from scene
  19216. this.getScene().removeTransformNode(this);
  19217. this.onAfterWorldMatrixUpdateObservable.clear();
  19218. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19219. };
  19220. // Statics
  19221. TransformNode.BILLBOARDMODE_NONE = 0;
  19222. TransformNode.BILLBOARDMODE_X = 1;
  19223. TransformNode.BILLBOARDMODE_Y = 2;
  19224. TransformNode.BILLBOARDMODE_Z = 4;
  19225. TransformNode.BILLBOARDMODE_ALL = 7;
  19226. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19227. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19228. __decorate([
  19229. BABYLON.serializeAsVector3()
  19230. ], TransformNode.prototype, "_rotation", void 0);
  19231. __decorate([
  19232. BABYLON.serializeAsQuaternion()
  19233. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19234. __decorate([
  19235. BABYLON.serializeAsVector3()
  19236. ], TransformNode.prototype, "_scaling", void 0);
  19237. __decorate([
  19238. BABYLON.serialize()
  19239. ], TransformNode.prototype, "billboardMode", void 0);
  19240. __decorate([
  19241. BABYLON.serialize()
  19242. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19243. __decorate([
  19244. BABYLON.serialize()
  19245. ], TransformNode.prototype, "infiniteDistance", void 0);
  19246. __decorate([
  19247. BABYLON.serializeAsVector3()
  19248. ], TransformNode.prototype, "position", void 0);
  19249. return TransformNode;
  19250. }(BABYLON.Node));
  19251. BABYLON.TransformNode = TransformNode;
  19252. })(BABYLON || (BABYLON = {}));
  19253. //# sourceMappingURL=babylon.transformNode.js.map
  19254. var BABYLON;
  19255. (function (BABYLON) {
  19256. /**
  19257. * Class used to store all common mesh properties
  19258. */
  19259. var AbstractMesh = /** @class */ (function (_super) {
  19260. __extends(AbstractMesh, _super);
  19261. // Constructor
  19262. /**
  19263. * Creates a new AbstractMesh
  19264. * @param name defines the name of the mesh
  19265. * @param scene defines the hosting scene
  19266. */
  19267. function AbstractMesh(name, scene) {
  19268. if (scene === void 0) { scene = null; }
  19269. var _this = _super.call(this, name, scene, false) || this;
  19270. _this._facetNb = 0; // facet number
  19271. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19272. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19273. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19274. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19275. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19276. _this._subDiv = {
  19277. max: 1,
  19278. X: 1,
  19279. Y: 1,
  19280. Z: 1
  19281. };
  19282. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19283. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19284. // Events
  19285. /**
  19286. * An event triggered when this mesh collides with another one
  19287. */
  19288. _this.onCollideObservable = new BABYLON.Observable();
  19289. /**
  19290. * An event triggered when the collision's position changes
  19291. */
  19292. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19293. /**
  19294. * An event triggered when material is changed
  19295. */
  19296. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19297. // Properties
  19298. /**
  19299. * Gets or sets the orientation for POV movement & rotation
  19300. */
  19301. _this.definedFacingForward = true;
  19302. /**
  19303. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19304. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19305. * * 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.
  19306. * @see http://doc.babylonjs.com/features/occlusionquery
  19307. */
  19308. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19309. /**
  19310. * 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:
  19311. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19312. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19313. * * 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.
  19314. * @see http://doc.babylonjs.com/features/occlusionquery
  19315. */
  19316. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19317. /**
  19318. * 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.
  19319. * The default value is -1 which means don't break the query and wait till the result
  19320. * @see http://doc.babylonjs.com/features/occlusionquery
  19321. */
  19322. _this.occlusionRetryCount = -1;
  19323. _this._occlusionInternalRetryCounter = 0;
  19324. _this._isOccluded = false;
  19325. _this._isOcclusionQueryInProgress = false;
  19326. _this._visibility = 1.0;
  19327. /** Gets or sets the alpha index used to sort transparent meshes
  19328. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19329. */
  19330. _this.alphaIndex = Number.MAX_VALUE;
  19331. /**
  19332. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19333. */
  19334. _this.isVisible = true;
  19335. /**
  19336. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19337. */
  19338. _this.isPickable = true;
  19339. /**
  19340. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19341. */
  19342. _this.showBoundingBox = false;
  19343. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19344. _this.showSubMeshesBoundingBox = false;
  19345. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19346. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19347. */
  19348. _this.isBlocker = false;
  19349. /**
  19350. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19351. */
  19352. _this.enablePointerMoveEvents = false;
  19353. /**
  19354. * Specifies the rendering group id for this mesh (0 by default)
  19355. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19356. */
  19357. _this.renderingGroupId = 0;
  19358. _this._receiveShadows = false;
  19359. /**
  19360. * Gets or sets a boolean indicating if the outline must be rendered as well
  19361. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19362. */
  19363. _this.renderOutline = false;
  19364. /** Defines color to use when rendering outline */
  19365. _this.outlineColor = BABYLON.Color3.Red();
  19366. /** Define width to use when rendering outline */
  19367. _this.outlineWidth = 0.02;
  19368. /**
  19369. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19370. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19371. */
  19372. _this.renderOverlay = false;
  19373. /** Defines color to use when rendering overlay */
  19374. _this.overlayColor = BABYLON.Color3.Red();
  19375. /** Defines alpha to use when rendering overlay */
  19376. _this.overlayAlpha = 0.5;
  19377. _this._hasVertexAlpha = false;
  19378. _this._useVertexColors = true;
  19379. _this._computeBonesUsingShaders = true;
  19380. _this._numBoneInfluencers = 4;
  19381. _this._applyFog = true;
  19382. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19383. _this.useOctreeForRenderingSelection = true;
  19384. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19385. _this.useOctreeForPicking = true;
  19386. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19387. _this.useOctreeForCollisions = true;
  19388. _this._layerMask = 0x0FFFFFFF;
  19389. /**
  19390. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19391. */
  19392. _this.alwaysSelectAsActiveMesh = false;
  19393. /**
  19394. * Gets or sets the current action manager
  19395. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19396. */
  19397. _this.actionManager = null;
  19398. /**
  19399. * Gets or sets impostor used for physic simulation
  19400. * @see http://doc.babylonjs.com/features/physics_engine
  19401. */
  19402. _this.physicsImpostor = null;
  19403. // Collisions
  19404. _this._checkCollisions = false;
  19405. _this._collisionMask = -1;
  19406. _this._collisionGroup = -1;
  19407. /**
  19408. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19409. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19410. */
  19411. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19412. /**
  19413. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19414. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19415. */
  19416. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19417. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19418. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19419. // Edges
  19420. /**
  19421. * Defines edge width used when edgesRenderer is enabled
  19422. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19423. */
  19424. _this.edgesWidth = 1;
  19425. /**
  19426. * Defines edge color used when edgesRenderer is enabled
  19427. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19428. */
  19429. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19430. // Cache
  19431. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19432. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19433. /** @hidden */
  19434. _this._renderId = 0;
  19435. /** @hidden */
  19436. _this._intersectionsInProgress = new Array();
  19437. /** @hidden */
  19438. _this._unIndexed = false;
  19439. /** @hidden */
  19440. _this._lightSources = new Array();
  19441. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19442. if (collidedMesh === void 0) { collidedMesh = null; }
  19443. //TODO move this to the collision coordinator!
  19444. if (_this.getScene().workerCollisions)
  19445. newPosition.multiplyInPlace(_this._collider._radius);
  19446. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19447. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19448. _this.position.addInPlace(_this._diffPositionForCollisions);
  19449. }
  19450. if (collidedMesh) {
  19451. _this.onCollideObservable.notifyObservers(collidedMesh);
  19452. }
  19453. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19454. };
  19455. _this.getScene().addMesh(_this);
  19456. _this._resyncLightSources();
  19457. return _this;
  19458. }
  19459. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19460. /**
  19461. * No billboard
  19462. */
  19463. get: function () {
  19464. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19470. /** Billboard on X axis */
  19471. get: function () {
  19472. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19478. /** Billboard on Y axis */
  19479. get: function () {
  19480. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19486. /** Billboard on Z axis */
  19487. get: function () {
  19488. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19494. /** Billboard on all axes */
  19495. get: function () {
  19496. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19502. /**
  19503. * Gets the number of facets in the mesh
  19504. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19505. */
  19506. get: function () {
  19507. return this._facetNb;
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19513. /**
  19514. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19515. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19516. */
  19517. get: function () {
  19518. return this._partitioningSubdivisions;
  19519. },
  19520. set: function (nb) {
  19521. this._partitioningSubdivisions = nb;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19527. /**
  19528. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19529. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19530. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19531. */
  19532. get: function () {
  19533. return this._partitioningBBoxRatio;
  19534. },
  19535. set: function (ratio) {
  19536. this._partitioningBBoxRatio = ratio;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19542. /**
  19543. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19544. * Works only for updatable meshes.
  19545. * Doesn't work with multi-materials
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19547. */
  19548. get: function () {
  19549. return this._facetDepthSort;
  19550. },
  19551. set: function (sort) {
  19552. this._facetDepthSort = sort;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19558. /**
  19559. * The location (Vector3) where the facet depth sort must be computed from.
  19560. * By default, the active camera position.
  19561. * Used only when facet depth sort is enabled
  19562. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19563. */
  19564. get: function () {
  19565. return this._facetDepthSortFrom;
  19566. },
  19567. set: function (location) {
  19568. this._facetDepthSortFrom = location;
  19569. },
  19570. enumerable: true,
  19571. configurable: true
  19572. });
  19573. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19574. /**
  19575. * gets a boolean indicating if facetData is enabled
  19576. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19577. */
  19578. get: function () {
  19579. return this._facetDataEnabled;
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. /** @hidden */
  19585. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19586. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19587. return false;
  19588. }
  19589. this._markSubMeshesAsMiscDirty();
  19590. return true;
  19591. };
  19592. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19593. /** Set a function to call when this mesh collides with another one */
  19594. set: function (callback) {
  19595. if (this._onCollideObserver) {
  19596. this.onCollideObservable.remove(this._onCollideObserver);
  19597. }
  19598. this._onCollideObserver = this.onCollideObservable.add(callback);
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19604. /** Set a function to call when the collision's position changes */
  19605. set: function (callback) {
  19606. if (this._onCollisionPositionChangeObserver) {
  19607. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19608. }
  19609. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19615. /**
  19616. * 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
  19617. * @see http://doc.babylonjs.com/features/occlusionquery
  19618. */
  19619. get: function () {
  19620. return this._isOccluded;
  19621. },
  19622. set: function (value) {
  19623. this._isOccluded = value;
  19624. },
  19625. enumerable: true,
  19626. configurable: true
  19627. });
  19628. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19629. /**
  19630. * Flag to check the progress status of the query
  19631. * @see http://doc.babylonjs.com/features/occlusionquery
  19632. */
  19633. get: function () {
  19634. return this._isOcclusionQueryInProgress;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19640. /**
  19641. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19642. */
  19643. get: function () {
  19644. return this._visibility;
  19645. },
  19646. /**
  19647. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19648. */
  19649. set: function (value) {
  19650. if (this._visibility === value) {
  19651. return;
  19652. }
  19653. this._visibility = value;
  19654. this._markSubMeshesAsMiscDirty();
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(AbstractMesh.prototype, "material", {
  19660. /** Gets or sets current material */
  19661. get: function () {
  19662. return this._material;
  19663. },
  19664. set: function (value) {
  19665. if (this._material === value) {
  19666. return;
  19667. }
  19668. this._material = value;
  19669. if (this.onMaterialChangedObservable.hasObservers) {
  19670. this.onMaterialChangedObservable.notifyObservers(this);
  19671. }
  19672. if (!this.subMeshes) {
  19673. return;
  19674. }
  19675. this._unBindEffect();
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19681. /**
  19682. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19683. * @see http://doc.babylonjs.com/babylon101/shadows
  19684. */
  19685. get: function () {
  19686. return this._receiveShadows;
  19687. },
  19688. set: function (value) {
  19689. if (this._receiveShadows === value) {
  19690. return;
  19691. }
  19692. this._receiveShadows = value;
  19693. this._markSubMeshesAsLightDirty();
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19699. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19700. get: function () {
  19701. return this._hasVertexAlpha;
  19702. },
  19703. set: function (value) {
  19704. if (this._hasVertexAlpha === value) {
  19705. return;
  19706. }
  19707. this._hasVertexAlpha = value;
  19708. this._markSubMeshesAsAttributesDirty();
  19709. this._markSubMeshesAsMiscDirty();
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19715. /** 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) */
  19716. get: function () {
  19717. return this._useVertexColors;
  19718. },
  19719. set: function (value) {
  19720. if (this._useVertexColors === value) {
  19721. return;
  19722. }
  19723. this._useVertexColors = value;
  19724. this._markSubMeshesAsAttributesDirty();
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19730. /**
  19731. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19732. */
  19733. get: function () {
  19734. return this._computeBonesUsingShaders;
  19735. },
  19736. set: function (value) {
  19737. if (this._computeBonesUsingShaders === value) {
  19738. return;
  19739. }
  19740. this._computeBonesUsingShaders = value;
  19741. this._markSubMeshesAsAttributesDirty();
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19747. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19748. get: function () {
  19749. return this._numBoneInfluencers;
  19750. },
  19751. set: function (value) {
  19752. if (this._numBoneInfluencers === value) {
  19753. return;
  19754. }
  19755. this._numBoneInfluencers = value;
  19756. this._markSubMeshesAsAttributesDirty();
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19762. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19763. get: function () {
  19764. return this._applyFog;
  19765. },
  19766. set: function (value) {
  19767. if (this._applyFog === value) {
  19768. return;
  19769. }
  19770. this._applyFog = value;
  19771. this._markSubMeshesAsMiscDirty();
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19777. /**
  19778. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19779. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19780. */
  19781. get: function () {
  19782. return this._layerMask;
  19783. },
  19784. set: function (value) {
  19785. if (value === this._layerMask) {
  19786. return;
  19787. }
  19788. this._layerMask = value;
  19789. this._resyncLightSources();
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19795. /**
  19796. * Gets or sets a collision mask used to mask collisions (default is -1).
  19797. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19798. */
  19799. get: function () {
  19800. return this._collisionMask;
  19801. },
  19802. set: function (mask) {
  19803. this._collisionMask = !isNaN(mask) ? mask : -1;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19809. /**
  19810. * Gets or sets the current collision group mask (-1 by default).
  19811. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19812. */
  19813. get: function () {
  19814. return this._collisionGroup;
  19815. },
  19816. set: function (mask) {
  19817. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19823. /** @hidden */
  19824. get: function () {
  19825. return null;
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19831. get: function () {
  19832. return this._skeleton;
  19833. },
  19834. /**
  19835. * Gets or sets a skeleton to apply skining transformations
  19836. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19837. */
  19838. set: function (value) {
  19839. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19840. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19841. }
  19842. if (value && value.needInitialSkinMatrix) {
  19843. value._registerMeshWithPoseMatrix(this);
  19844. }
  19845. this._skeleton = value;
  19846. if (!this._skeleton) {
  19847. this._bonesTransformMatrices = null;
  19848. }
  19849. this._markSubMeshesAsAttributesDirty();
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. /**
  19855. * Returns the string "AbstractMesh"
  19856. * @returns "AbstractMesh"
  19857. */
  19858. AbstractMesh.prototype.getClassName = function () {
  19859. return "AbstractMesh";
  19860. };
  19861. /**
  19862. * Gets a string representation of the current mesh
  19863. * @param fullDetails defines a boolean indicating if full details must be included
  19864. * @returns a string representation of the current mesh
  19865. */
  19866. AbstractMesh.prototype.toString = function (fullDetails) {
  19867. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19868. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19869. if (this._skeleton) {
  19870. ret += ", skeleton: " + this._skeleton.name;
  19871. }
  19872. if (fullDetails) {
  19873. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19874. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19875. }
  19876. return ret;
  19877. };
  19878. /** @hidden */
  19879. AbstractMesh.prototype._rebuild = function () {
  19880. if (this._occlusionQuery) {
  19881. this._occlusionQuery = null;
  19882. }
  19883. if (this._edgesRenderer) {
  19884. this._edgesRenderer._rebuild();
  19885. }
  19886. if (!this.subMeshes) {
  19887. return;
  19888. }
  19889. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19890. var subMesh = _a[_i];
  19891. subMesh._rebuild();
  19892. }
  19893. };
  19894. /** @hidden */
  19895. AbstractMesh.prototype._resyncLightSources = function () {
  19896. this._lightSources.length = 0;
  19897. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19898. var light = _a[_i];
  19899. if (!light.isEnabled()) {
  19900. continue;
  19901. }
  19902. if (light.canAffectMesh(this)) {
  19903. this._lightSources.push(light);
  19904. }
  19905. }
  19906. this._markSubMeshesAsLightDirty();
  19907. };
  19908. /** @hidden */
  19909. AbstractMesh.prototype._resyncLighSource = function (light) {
  19910. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19911. var index = this._lightSources.indexOf(light);
  19912. if (index === -1) {
  19913. if (!isIn) {
  19914. return;
  19915. }
  19916. this._lightSources.push(light);
  19917. }
  19918. else {
  19919. if (isIn) {
  19920. return;
  19921. }
  19922. this._lightSources.splice(index, 1);
  19923. }
  19924. this._markSubMeshesAsLightDirty();
  19925. };
  19926. /** @hidden */
  19927. AbstractMesh.prototype._unBindEffect = function () {
  19928. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19929. var subMesh = _a[_i];
  19930. subMesh.setEffect(null);
  19931. }
  19932. };
  19933. /** @hidden */
  19934. AbstractMesh.prototype._removeLightSource = function (light) {
  19935. var index = this._lightSources.indexOf(light);
  19936. if (index === -1) {
  19937. return;
  19938. }
  19939. this._lightSources.splice(index, 1);
  19940. this._markSubMeshesAsLightDirty();
  19941. };
  19942. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  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. if (subMesh._materialDefines) {
  19949. func(subMesh._materialDefines);
  19950. }
  19951. }
  19952. };
  19953. /** @hidden */
  19954. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19955. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19956. };
  19957. /** @hidden */
  19958. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19959. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19960. };
  19961. /** @hidden */
  19962. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19963. if (!this.subMeshes) {
  19964. return;
  19965. }
  19966. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19967. var subMesh = _a[_i];
  19968. var material = subMesh.getMaterial();
  19969. if (material) {
  19970. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19971. }
  19972. }
  19973. };
  19974. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19975. /**
  19976. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19977. */
  19978. get: function () {
  19979. return this._scaling;
  19980. },
  19981. set: function (newScaling) {
  19982. this._scaling = newScaling;
  19983. if (this.physicsImpostor) {
  19984. this.physicsImpostor.forceUpdate();
  19985. }
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. // Methods
  19991. /**
  19992. * Disables the mesh edge rendering mode
  19993. * @returns the currentAbstractMesh
  19994. */
  19995. AbstractMesh.prototype.disableEdgesRendering = function () {
  19996. if (this._edgesRenderer) {
  19997. this._edgesRenderer.dispose();
  19998. this._edgesRenderer = null;
  19999. }
  20000. return this;
  20001. };
  20002. /**
  20003. * Enables the edge rendering mode on the mesh.
  20004. * This mode makes the mesh edges visible
  20005. * @param epsilon defines the maximal distance between two angles to detect a face
  20006. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20007. * @returns the currentAbstractMesh
  20008. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20009. */
  20010. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20011. if (epsilon === void 0) { epsilon = 0.95; }
  20012. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20013. this.disableEdgesRendering();
  20014. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20015. return this;
  20016. };
  20017. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20018. /**
  20019. * Returns true if the mesh is blocked. Implemented by child classes
  20020. */
  20021. get: function () {
  20022. return false;
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. /**
  20028. * Returns the mesh itself by default. Implemented by child classes
  20029. * @param camera defines the camera to use to pick the right LOD level
  20030. * @returns the currentAbstractMesh
  20031. */
  20032. AbstractMesh.prototype.getLOD = function (camera) {
  20033. return this;
  20034. };
  20035. /**
  20036. * Returns 0 by default. Implemented by child classes
  20037. * @returns an integer
  20038. */
  20039. AbstractMesh.prototype.getTotalVertices = function () {
  20040. return 0;
  20041. };
  20042. /**
  20043. * Returns null by default. Implemented by child classes
  20044. * @returns null
  20045. */
  20046. AbstractMesh.prototype.getIndices = function () {
  20047. return null;
  20048. };
  20049. /**
  20050. * Returns the array of the requested vertex data kind. Implemented by child classes
  20051. * @param kind defines the vertex data kind to use
  20052. * @returns null
  20053. */
  20054. AbstractMesh.prototype.getVerticesData = function (kind) {
  20055. return null;
  20056. };
  20057. /**
  20058. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20059. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20060. * Note that a new underlying VertexBuffer object is created each call.
  20061. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20062. * @param kind defines vertex data kind:
  20063. * * BABYLON.VertexBuffer.PositionKind
  20064. * * BABYLON.VertexBuffer.UVKind
  20065. * * BABYLON.VertexBuffer.UV2Kind
  20066. * * BABYLON.VertexBuffer.UV3Kind
  20067. * * BABYLON.VertexBuffer.UV4Kind
  20068. * * BABYLON.VertexBuffer.UV5Kind
  20069. * * BABYLON.VertexBuffer.UV6Kind
  20070. * * BABYLON.VertexBuffer.ColorKind
  20071. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20072. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20073. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20074. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20075. * @param data defines the data source
  20076. * @param updatable defines if the data must be flagged as updatable (or static)
  20077. * @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
  20078. * @returns the current mesh
  20079. */
  20080. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20081. return this;
  20082. };
  20083. /**
  20084. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20085. * If the mesh has no geometry, it is simply returned as it is.
  20086. * @param kind defines vertex data kind:
  20087. * * BABYLON.VertexBuffer.PositionKind
  20088. * * BABYLON.VertexBuffer.UVKind
  20089. * * BABYLON.VertexBuffer.UV2Kind
  20090. * * BABYLON.VertexBuffer.UV3Kind
  20091. * * BABYLON.VertexBuffer.UV4Kind
  20092. * * BABYLON.VertexBuffer.UV5Kind
  20093. * * BABYLON.VertexBuffer.UV6Kind
  20094. * * BABYLON.VertexBuffer.ColorKind
  20095. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20096. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20097. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20098. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20099. * @param data defines the data source
  20100. * @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
  20101. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20102. * @returns the current mesh
  20103. */
  20104. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20105. return this;
  20106. };
  20107. /**
  20108. * Sets the mesh indices,
  20109. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20110. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20111. * @param totalVertices Defines the total number of vertices
  20112. * @returns the current mesh
  20113. */
  20114. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20115. return this;
  20116. };
  20117. /**
  20118. * Gets a boolean indicating if specific vertex data is present
  20119. * @param kind defines the vertex data kind to use
  20120. * @returns true is data kind is present
  20121. */
  20122. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20123. return false;
  20124. };
  20125. /**
  20126. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20127. * @returns a BoundingInfo
  20128. */
  20129. AbstractMesh.prototype.getBoundingInfo = function () {
  20130. if (this._masterMesh) {
  20131. return this._masterMesh.getBoundingInfo();
  20132. }
  20133. if (!this._boundingInfo) {
  20134. // this._boundingInfo is being created here
  20135. this._updateBoundingInfo();
  20136. }
  20137. // cannot be null.
  20138. return this._boundingInfo;
  20139. };
  20140. /**
  20141. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20142. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20143. * @returns the current mesh
  20144. */
  20145. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20146. if (includeDescendants === void 0) { includeDescendants = true; }
  20147. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20148. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20149. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20150. if (maxDimension === 0) {
  20151. return this;
  20152. }
  20153. var scale = 1 / maxDimension;
  20154. this.scaling.scaleInPlace(scale);
  20155. return this;
  20156. };
  20157. /**
  20158. * Overwrite the current bounding info
  20159. * @param boundingInfo defines the new bounding info
  20160. * @returns the current mesh
  20161. */
  20162. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20163. this._boundingInfo = boundingInfo;
  20164. return this;
  20165. };
  20166. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20167. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20168. get: function () {
  20169. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20170. },
  20171. enumerable: true,
  20172. configurable: true
  20173. });
  20174. /** @hidden */
  20175. AbstractMesh.prototype._preActivate = function () {
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20179. };
  20180. /** @hidden */
  20181. AbstractMesh.prototype._activate = function (renderId) {
  20182. this._renderId = renderId;
  20183. };
  20184. /**
  20185. * Gets the current world matrix
  20186. * @returns a Matrix
  20187. */
  20188. AbstractMesh.prototype.getWorldMatrix = function () {
  20189. if (this._masterMesh) {
  20190. return this._masterMesh.getWorldMatrix();
  20191. }
  20192. return _super.prototype.getWorldMatrix.call(this);
  20193. };
  20194. /** @hidden */
  20195. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20196. if (this._masterMesh) {
  20197. return this._masterMesh._getWorldMatrixDeterminant();
  20198. }
  20199. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20200. };
  20201. // ================================== Point of View Movement =================================
  20202. /**
  20203. * Perform relative position change from the point of view of behind the front of the mesh.
  20204. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20205. * Supports definition of mesh facing forward or backward
  20206. * @param amountRight defines the distance on the right axis
  20207. * @param amountUp defines the distance on the up axis
  20208. * @param amountForward defines the distance on the forward axis
  20209. * @returns the current mesh
  20210. */
  20211. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20212. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20213. return this;
  20214. };
  20215. /**
  20216. * Calculate relative position change from the point of view of behind the front of the mesh.
  20217. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20218. * Supports definition of mesh facing forward or backward
  20219. * @param amountRight defines the distance on the right axis
  20220. * @param amountUp defines the distance on the up axis
  20221. * @param amountForward defines the distance on the forward axis
  20222. * @returns the new displacement vector
  20223. */
  20224. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20225. var rotMatrix = new BABYLON.Matrix();
  20226. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20227. rotQuaternion.toRotationMatrix(rotMatrix);
  20228. var translationDelta = BABYLON.Vector3.Zero();
  20229. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20231. return translationDelta;
  20232. };
  20233. // ================================== Point of View Rotation =================================
  20234. /**
  20235. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20236. * Supports definition of mesh facing forward or backward
  20237. * @param flipBack defines the flip
  20238. * @param twirlClockwise defines the twirl
  20239. * @param tiltRight defines the tilt
  20240. * @returns the current mesh
  20241. */
  20242. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20243. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20244. return this;
  20245. };
  20246. /**
  20247. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20248. * Supports definition of mesh facing forward or backward.
  20249. * @param flipBack defines the flip
  20250. * @param twirlClockwise defines the twirl
  20251. * @param tiltRight defines the tilt
  20252. * @returns the new rotation vector
  20253. */
  20254. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20255. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20256. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20257. };
  20258. /**
  20259. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20260. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20261. * @returns the new bounding vectors
  20262. */
  20263. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20264. if (includeDescendants === void 0) { includeDescendants = true; }
  20265. // Ensures that all world matrix will be recomputed.
  20266. this.getScene().incrementRenderId();
  20267. this.computeWorldMatrix(true);
  20268. var min;
  20269. var max;
  20270. var boundingInfo = this.getBoundingInfo();
  20271. if (!this.subMeshes) {
  20272. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20273. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20274. }
  20275. else {
  20276. min = boundingInfo.boundingBox.minimumWorld;
  20277. max = boundingInfo.boundingBox.maximumWorld;
  20278. }
  20279. if (includeDescendants) {
  20280. var descendants = this.getDescendants(false);
  20281. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20282. var descendant = descendants_1[_i];
  20283. var childMesh = descendant;
  20284. childMesh.computeWorldMatrix(true);
  20285. //make sure we have the needed params to get mix and max
  20286. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20287. continue;
  20288. }
  20289. var childBoundingInfo = childMesh.getBoundingInfo();
  20290. var boundingBox = childBoundingInfo.boundingBox;
  20291. var minBox = boundingBox.minimumWorld;
  20292. var maxBox = boundingBox.maximumWorld;
  20293. BABYLON.Tools.CheckExtends(minBox, min, max);
  20294. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20295. }
  20296. }
  20297. return {
  20298. min: min,
  20299. max: max
  20300. };
  20301. };
  20302. /** @hidden */
  20303. AbstractMesh.prototype._updateBoundingInfo = function () {
  20304. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20305. this._boundingInfo.update(this.worldMatrixFromCache);
  20306. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20307. return this;
  20308. };
  20309. /** @hidden */
  20310. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20311. if (!this.subMeshes) {
  20312. return this;
  20313. }
  20314. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20315. var subMesh = this.subMeshes[subIndex];
  20316. if (!subMesh.IsGlobal) {
  20317. subMesh.updateBoundingInfo(matrix);
  20318. }
  20319. }
  20320. return this;
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20324. // Bounding info
  20325. this._updateBoundingInfo();
  20326. };
  20327. /**
  20328. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20329. * A mesh is in the frustum if its bounding box intersects the frustum
  20330. * @param frustumPlanes defines the frustum to test
  20331. * @returns true if the mesh is in the frustum planes
  20332. */
  20333. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20334. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20335. };
  20336. /**
  20337. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20338. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20339. * @param frustumPlanes defines the frustum to test
  20340. * @returns true if the mesh is completely in the frustum planes
  20341. */
  20342. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20343. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20344. };
  20345. /**
  20346. * True if the mesh intersects another mesh or a SolidParticle object
  20347. * @param mesh defines a target mesh or SolidParticle to test
  20348. * @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)
  20349. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20350. * @returns true if there is an intersection
  20351. */
  20352. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20353. if (precise === void 0) { precise = false; }
  20354. if (!this._boundingInfo || !mesh._boundingInfo) {
  20355. return false;
  20356. }
  20357. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20358. return true;
  20359. }
  20360. if (includeDescendants) {
  20361. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20362. var child = _a[_i];
  20363. if (child.intersectsMesh(mesh, precise, true)) {
  20364. return true;
  20365. }
  20366. }
  20367. }
  20368. return false;
  20369. };
  20370. /**
  20371. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20372. * @param point defines the point to test
  20373. * @returns true if there is an intersection
  20374. */
  20375. AbstractMesh.prototype.intersectsPoint = function (point) {
  20376. if (!this._boundingInfo) {
  20377. return false;
  20378. }
  20379. return this._boundingInfo.intersectsPoint(point);
  20380. };
  20381. /**
  20382. * Gets the current physics impostor
  20383. * @see http://doc.babylonjs.com/features/physics_engine
  20384. * @returns a physics impostor or null
  20385. */
  20386. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20387. return this.physicsImpostor;
  20388. };
  20389. /**
  20390. * Gets the position of the current mesh in camera space
  20391. * @param camera defines the camera to use
  20392. * @returns a position
  20393. */
  20394. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20395. if (camera === void 0) { camera = null; }
  20396. if (!camera) {
  20397. camera = this.getScene().activeCamera;
  20398. }
  20399. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20400. };
  20401. /**
  20402. * Returns the distance from the mesh to the active camera
  20403. * @param camera defines the camera to use
  20404. * @returns the distance
  20405. */
  20406. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20407. if (camera === void 0) { camera = null; }
  20408. if (!camera) {
  20409. camera = this.getScene().activeCamera;
  20410. }
  20411. return this.absolutePosition.subtract(camera.position).length();
  20412. };
  20413. /**
  20414. * Apply a physic impulse to the mesh
  20415. * @param force defines the force to apply
  20416. * @param contactPoint defines where to apply the force
  20417. * @returns the current mesh
  20418. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20419. */
  20420. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20421. if (!this.physicsImpostor) {
  20422. return this;
  20423. }
  20424. this.physicsImpostor.applyImpulse(force, contactPoint);
  20425. return this;
  20426. };
  20427. /**
  20428. * Creates a physic joint between two meshes
  20429. * @param otherMesh defines the other mesh to use
  20430. * @param pivot1 defines the pivot to use on this mesh
  20431. * @param pivot2 defines the pivot to use on the other mesh
  20432. * @param options defines additional options (can be plugin dependent)
  20433. * @returns the current mesh
  20434. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20435. */
  20436. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20437. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20438. return this;
  20439. }
  20440. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20441. mainPivot: pivot1,
  20442. connectedPivot: pivot2,
  20443. nativeParams: options
  20444. });
  20445. return this;
  20446. };
  20447. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20448. // Collisions
  20449. /**
  20450. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20451. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20452. */
  20453. get: function () {
  20454. return this._checkCollisions;
  20455. },
  20456. set: function (collisionEnabled) {
  20457. this._checkCollisions = collisionEnabled;
  20458. if (this.getScene().workerCollisions) {
  20459. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20460. }
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20466. /**
  20467. * Gets Collider object used to compute collisions (not physics)
  20468. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20469. */
  20470. get: function () {
  20471. return this._collider;
  20472. },
  20473. enumerable: true,
  20474. configurable: true
  20475. });
  20476. /**
  20477. * Move the mesh using collision engine
  20478. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20479. * @param displacement defines the requested displacement vector
  20480. * @returns the current mesh
  20481. */
  20482. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20483. var globalPosition = this.getAbsolutePosition();
  20484. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20485. if (!this._collider) {
  20486. this._collider = new BABYLON.Collider();
  20487. }
  20488. this._collider._radius = this.ellipsoid;
  20489. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20490. return this;
  20491. };
  20492. // Submeshes octree
  20493. /**
  20494. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20495. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20496. * @param maxCapacity defines the maximum size of each block (64 by default)
  20497. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20498. * @returns the new octree
  20499. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20500. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20501. */
  20502. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20503. if (maxCapacity === void 0) { maxCapacity = 64; }
  20504. if (maxDepth === void 0) { maxDepth = 2; }
  20505. if (!this._submeshesOctree) {
  20506. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20507. }
  20508. this.computeWorldMatrix(true);
  20509. var boundingInfo = this.getBoundingInfo();
  20510. // Update octree
  20511. var bbox = boundingInfo.boundingBox;
  20512. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20513. return this._submeshesOctree;
  20514. };
  20515. // Collisions
  20516. /** @hidden */
  20517. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20518. this._generatePointsArray();
  20519. if (!this._positions) {
  20520. return this;
  20521. }
  20522. // Transformation
  20523. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20524. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20525. subMesh._lastColliderWorldVertices = [];
  20526. subMesh._trianglePlanes = [];
  20527. var start = subMesh.verticesStart;
  20528. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20529. for (var i = start; i < end; i++) {
  20530. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20531. }
  20532. }
  20533. // Collide
  20534. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20535. if (collider.collisionFound) {
  20536. collider.collidedMesh = this;
  20537. }
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20542. var subMeshes;
  20543. var len;
  20544. // Octrees
  20545. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20546. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20547. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20548. len = intersections.length;
  20549. subMeshes = intersections.data;
  20550. }
  20551. else {
  20552. subMeshes = this.subMeshes;
  20553. len = subMeshes.length;
  20554. }
  20555. for (var index = 0; index < len; index++) {
  20556. var subMesh = subMeshes[index];
  20557. // Bounding test
  20558. if (len > 1 && !subMesh._checkCollision(collider))
  20559. continue;
  20560. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20561. }
  20562. return this;
  20563. };
  20564. /** @hidden */
  20565. AbstractMesh.prototype._checkCollision = function (collider) {
  20566. // Bounding box test
  20567. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20568. return this;
  20569. // Transformation matrix
  20570. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20571. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20572. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20573. return this;
  20574. };
  20575. // Picking
  20576. /** @hidden */
  20577. AbstractMesh.prototype._generatePointsArray = function () {
  20578. return false;
  20579. };
  20580. /**
  20581. * Checks if the passed Ray intersects with the mesh
  20582. * @param ray defines the ray to use
  20583. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20584. * @returns the picking info
  20585. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20586. */
  20587. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20588. var pickingInfo = new BABYLON.PickingInfo();
  20589. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20590. return pickingInfo;
  20591. }
  20592. if (!this._generatePointsArray()) {
  20593. return pickingInfo;
  20594. }
  20595. var intersectInfo = null;
  20596. // Octrees
  20597. var subMeshes;
  20598. var len;
  20599. if (this._submeshesOctree && this.useOctreeForPicking) {
  20600. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20601. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20602. len = intersections.length;
  20603. subMeshes = intersections.data;
  20604. }
  20605. else {
  20606. subMeshes = this.subMeshes;
  20607. len = subMeshes.length;
  20608. }
  20609. for (var index = 0; index < len; index++) {
  20610. var subMesh = subMeshes[index];
  20611. // Bounding test
  20612. if (len > 1 && !subMesh.canIntersects(ray))
  20613. continue;
  20614. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20615. if (currentIntersectInfo) {
  20616. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20617. intersectInfo = currentIntersectInfo;
  20618. intersectInfo.subMeshId = index;
  20619. if (fastCheck) {
  20620. break;
  20621. }
  20622. }
  20623. }
  20624. }
  20625. if (intersectInfo) {
  20626. // Get picked point
  20627. var world = this.getWorldMatrix();
  20628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20629. var direction = ray.direction.clone();
  20630. direction = direction.scale(intersectInfo.distance);
  20631. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20632. var pickedPoint = worldOrigin.add(worldDirection);
  20633. // Return result
  20634. pickingInfo.hit = true;
  20635. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20636. pickingInfo.pickedPoint = pickedPoint;
  20637. pickingInfo.pickedMesh = this;
  20638. pickingInfo.bu = intersectInfo.bu || 0;
  20639. pickingInfo.bv = intersectInfo.bv || 0;
  20640. pickingInfo.faceId = intersectInfo.faceId;
  20641. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20642. return pickingInfo;
  20643. }
  20644. return pickingInfo;
  20645. };
  20646. /**
  20647. * Clones the current mesh
  20648. * @param name defines the mesh name
  20649. * @param newParent defines the new mesh parent
  20650. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20651. * @returns the new mesh
  20652. */
  20653. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20654. return null;
  20655. };
  20656. /**
  20657. * Disposes all the submeshes of the current meshnp
  20658. * @returns the current mesh
  20659. */
  20660. AbstractMesh.prototype.releaseSubMeshes = function () {
  20661. if (this.subMeshes) {
  20662. while (this.subMeshes.length) {
  20663. this.subMeshes[0].dispose();
  20664. }
  20665. }
  20666. else {
  20667. this.subMeshes = new Array();
  20668. }
  20669. return this;
  20670. };
  20671. /**
  20672. * Releases resources associated with this abstract mesh.
  20673. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20674. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20675. */
  20676. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20677. var _this = this;
  20678. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20679. var index;
  20680. // Smart Array Retainers.
  20681. this.getScene().freeActiveMeshes();
  20682. this.getScene().freeRenderingGroups();
  20683. // Action manager
  20684. if (this.actionManager !== undefined && this.actionManager !== null) {
  20685. this.actionManager.dispose();
  20686. this.actionManager = null;
  20687. }
  20688. // Skeleton
  20689. this._skeleton = null;
  20690. // Physics
  20691. if (this.physicsImpostor) {
  20692. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20693. }
  20694. // Intersections in progress
  20695. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20696. var other = this._intersectionsInProgress[index];
  20697. var pos = other._intersectionsInProgress.indexOf(this);
  20698. other._intersectionsInProgress.splice(pos, 1);
  20699. }
  20700. this._intersectionsInProgress = [];
  20701. // Lights
  20702. var lights = this.getScene().lights;
  20703. lights.forEach(function (light) {
  20704. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20705. if (meshIndex !== -1) {
  20706. light.includedOnlyMeshes.splice(meshIndex, 1);
  20707. }
  20708. meshIndex = light.excludedMeshes.indexOf(_this);
  20709. if (meshIndex !== -1) {
  20710. light.excludedMeshes.splice(meshIndex, 1);
  20711. }
  20712. // Shadow generators
  20713. var generator = light.getShadowGenerator();
  20714. if (generator) {
  20715. var shadowMap = generator.getShadowMap();
  20716. if (shadowMap && shadowMap.renderList) {
  20717. meshIndex = shadowMap.renderList.indexOf(_this);
  20718. if (meshIndex !== -1) {
  20719. shadowMap.renderList.splice(meshIndex, 1);
  20720. }
  20721. }
  20722. }
  20723. });
  20724. // Edges
  20725. if (this._edgesRenderer) {
  20726. this._edgesRenderer.dispose();
  20727. this._edgesRenderer = null;
  20728. }
  20729. // SubMeshes
  20730. if (this.getClassName() !== "InstancedMesh") {
  20731. this.releaseSubMeshes();
  20732. }
  20733. // Octree
  20734. var sceneOctree = this.getScene().selectionOctree;
  20735. if (sceneOctree !== undefined && sceneOctree !== null) {
  20736. var index = sceneOctree.dynamicContent.indexOf(this);
  20737. if (index !== -1) {
  20738. sceneOctree.dynamicContent.splice(index, 1);
  20739. }
  20740. }
  20741. // Query
  20742. var engine = this.getScene().getEngine();
  20743. if (this._occlusionQuery) {
  20744. this._isOcclusionQueryInProgress = false;
  20745. engine.deleteQuery(this._occlusionQuery);
  20746. this._occlusionQuery = null;
  20747. }
  20748. // Engine
  20749. engine.wipeCaches();
  20750. // Remove from scene
  20751. this.getScene().removeMesh(this);
  20752. if (disposeMaterialAndTextures) {
  20753. if (this.material) {
  20754. this.material.dispose(false, true);
  20755. }
  20756. }
  20757. if (!doNotRecurse) {
  20758. // Particles
  20759. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20760. if (this.getScene().particleSystems[index].emitter === this) {
  20761. this.getScene().particleSystems[index].dispose();
  20762. index--;
  20763. }
  20764. }
  20765. }
  20766. // facet data
  20767. if (this._facetDataEnabled) {
  20768. this.disableFacetData();
  20769. }
  20770. this.onAfterWorldMatrixUpdateObservable.clear();
  20771. this.onCollideObservable.clear();
  20772. this.onCollisionPositionChangeObservable.clear();
  20773. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20774. };
  20775. /**
  20776. * Adds the passed mesh as a child to the current mesh
  20777. * @param mesh defines the child mesh
  20778. * @returns the current mesh
  20779. */
  20780. AbstractMesh.prototype.addChild = function (mesh) {
  20781. mesh.setParent(this);
  20782. return this;
  20783. };
  20784. /**
  20785. * Removes the passed mesh from the current mesh children list
  20786. * @param mesh defines the child mesh
  20787. * @returns the current mesh
  20788. */
  20789. AbstractMesh.prototype.removeChild = function (mesh) {
  20790. mesh.setParent(null);
  20791. return this;
  20792. };
  20793. // Facet data
  20794. /** @hidden */
  20795. AbstractMesh.prototype._initFacetData = function () {
  20796. if (!this._facetNormals) {
  20797. this._facetNormals = new Array();
  20798. }
  20799. if (!this._facetPositions) {
  20800. this._facetPositions = new Array();
  20801. }
  20802. if (!this._facetPartitioning) {
  20803. this._facetPartitioning = new Array();
  20804. }
  20805. this._facetNb = (this.getIndices().length / 3) | 0;
  20806. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20807. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20808. for (var f = 0; f < this._facetNb; f++) {
  20809. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20810. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20811. }
  20812. this._facetDataEnabled = true;
  20813. return this;
  20814. };
  20815. /**
  20816. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20817. * This method can be called within the render loop.
  20818. * 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
  20819. * @returns the current mesh
  20820. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20821. */
  20822. AbstractMesh.prototype.updateFacetData = function () {
  20823. if (!this._facetDataEnabled) {
  20824. this._initFacetData();
  20825. }
  20826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20827. var indices = this.getIndices();
  20828. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20829. var bInfo = this.getBoundingInfo();
  20830. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20831. // init arrays, matrix and sort function on first call
  20832. this._facetDepthSortEnabled = true;
  20833. if (indices instanceof Uint16Array) {
  20834. this._depthSortedIndices = new Uint16Array(indices);
  20835. }
  20836. else if (indices instanceof Uint32Array) {
  20837. this._depthSortedIndices = new Uint32Array(indices);
  20838. }
  20839. else {
  20840. var needs32bits = false;
  20841. for (var i = 0; i < indices.length; i++) {
  20842. if (indices[i] > 65535) {
  20843. needs32bits = true;
  20844. break;
  20845. }
  20846. }
  20847. if (needs32bits) {
  20848. this._depthSortedIndices = new Uint32Array(indices);
  20849. }
  20850. else {
  20851. this._depthSortedIndices = new Uint16Array(indices);
  20852. }
  20853. }
  20854. this._facetDepthSortFunction = function (f1, f2) {
  20855. return (f2.sqDistance - f1.sqDistance);
  20856. };
  20857. if (!this._facetDepthSortFrom) {
  20858. var camera = this.getScene().activeCamera;
  20859. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20860. }
  20861. this._depthSortedFacets = [];
  20862. for (var f = 0; f < this._facetNb; f++) {
  20863. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20864. this._depthSortedFacets.push(depthSortedFacet);
  20865. }
  20866. this._invertedMatrix = BABYLON.Matrix.Identity();
  20867. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20868. }
  20869. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20870. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20871. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20872. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20873. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20874. this._subDiv.max = this._partitioningSubdivisions;
  20875. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20876. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20877. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20878. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20879. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20880. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20881. // set the parameters for ComputeNormals()
  20882. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20883. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20884. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20885. this._facetParameters.bInfo = bInfo;
  20886. this._facetParameters.bbSize = this._bbSize;
  20887. this._facetParameters.subDiv = this._subDiv;
  20888. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20889. this._facetParameters.depthSort = this._facetDepthSort;
  20890. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20891. this.computeWorldMatrix(true);
  20892. this._worldMatrix.invertToRef(this._invertedMatrix);
  20893. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20894. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20895. }
  20896. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20898. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20899. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20900. var l = (this._depthSortedIndices.length / 3) | 0;
  20901. for (var f = 0; f < l; f++) {
  20902. var sind = this._depthSortedFacets[f].ind;
  20903. this._depthSortedIndices[f * 3] = indices[sind];
  20904. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20905. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20906. }
  20907. this.updateIndices(this._depthSortedIndices);
  20908. }
  20909. return this;
  20910. };
  20911. /**
  20912. * Returns the facetLocalNormals array.
  20913. * The normals are expressed in the mesh local spac
  20914. * @returns an array of Vector3
  20915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20916. */
  20917. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20918. if (!this._facetNormals) {
  20919. this.updateFacetData();
  20920. }
  20921. return this._facetNormals;
  20922. };
  20923. /**
  20924. * Returns the facetLocalPositions array.
  20925. * The facet positions are expressed in the mesh local space
  20926. * @returns an array of Vector3
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20930. if (!this._facetPositions) {
  20931. this.updateFacetData();
  20932. }
  20933. return this._facetPositions;
  20934. };
  20935. /**
  20936. * Returns the facetLocalPartioning array
  20937. * @returns an array of array of numbers
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20941. if (!this._facetPartitioning) {
  20942. this.updateFacetData();
  20943. }
  20944. return this._facetPartitioning;
  20945. };
  20946. /**
  20947. * Returns the i-th facet position in the world system.
  20948. * This method allocates a new Vector3 per call
  20949. * @param i defines the facet index
  20950. * @returns a new Vector3
  20951. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20952. */
  20953. AbstractMesh.prototype.getFacetPosition = function (i) {
  20954. var pos = BABYLON.Vector3.Zero();
  20955. this.getFacetPositionToRef(i, pos);
  20956. return pos;
  20957. };
  20958. /**
  20959. * Sets the reference Vector3 with the i-th facet position in the world system
  20960. * @param i defines the facet index
  20961. * @param ref defines the target vector
  20962. * @returns the current mesh
  20963. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20964. */
  20965. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20966. var localPos = (this.getFacetLocalPositions())[i];
  20967. var world = this.getWorldMatrix();
  20968. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20969. return this;
  20970. };
  20971. /**
  20972. * Returns the i-th facet normal in the world system.
  20973. * This method allocates a new Vector3 per call
  20974. * @param i defines the facet index
  20975. * @returns a new Vector3
  20976. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20977. */
  20978. AbstractMesh.prototype.getFacetNormal = function (i) {
  20979. var norm = BABYLON.Vector3.Zero();
  20980. this.getFacetNormalToRef(i, norm);
  20981. return norm;
  20982. };
  20983. /**
  20984. * Sets the reference Vector3 with the i-th facet normal in the world system
  20985. * @param i defines the facet index
  20986. * @param ref defines the target vector
  20987. * @returns the current mesh
  20988. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20989. */
  20990. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20991. var localNorm = (this.getFacetLocalNormals())[i];
  20992. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20993. return this;
  20994. };
  20995. /**
  20996. * 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)
  20997. * @param x defines x coordinate
  20998. * @param y defines y coordinate
  20999. * @param z defines z coordinate
  21000. * @returns the array of facet indexes
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21004. var bInfo = this.getBoundingInfo();
  21005. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21006. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21007. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21008. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21009. return null;
  21010. }
  21011. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21012. };
  21013. /**
  21014. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21015. * @param projected sets as the (x,y,z) world projection on the facet
  21016. * @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
  21017. * @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
  21018. * @param x defines x coordinate
  21019. * @param y defines y coordinate
  21020. * @param z defines z coordinate
  21021. * @returns the face index if found (or null instead)
  21022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21023. */
  21024. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21025. if (checkFace === void 0) { checkFace = false; }
  21026. if (facing === void 0) { facing = true; }
  21027. var world = this.getWorldMatrix();
  21028. var invMat = BABYLON.Tmp.Matrix[5];
  21029. world.invertToRef(invMat);
  21030. var invVect = BABYLON.Tmp.Vector3[8];
  21031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21032. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21033. if (projected) {
  21034. // tranform the local computed projected vector to world coordinates
  21035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21036. }
  21037. return closest;
  21038. };
  21039. /**
  21040. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21041. * @param projected sets as the (x,y,z) local projection on the facet
  21042. * @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
  21043. * @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
  21044. * @param x defines x coordinate
  21045. * @param y defines y coordinate
  21046. * @param z defines z coordinate
  21047. * @returns the face index if found (or null instead)
  21048. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21049. */
  21050. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21051. if (checkFace === void 0) { checkFace = false; }
  21052. if (facing === void 0) { facing = true; }
  21053. var closest = null;
  21054. var tmpx = 0.0;
  21055. var tmpy = 0.0;
  21056. var tmpz = 0.0;
  21057. var d = 0.0; // tmp dot facet normal * facet position
  21058. var t0 = 0.0;
  21059. var projx = 0.0;
  21060. var projy = 0.0;
  21061. var projz = 0.0;
  21062. // Get all the facets in the same partitioning block than (x, y, z)
  21063. var facetPositions = this.getFacetLocalPositions();
  21064. var facetNormals = this.getFacetLocalNormals();
  21065. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21066. if (!facetsInBlock) {
  21067. return null;
  21068. }
  21069. // Get the closest facet to (x, y, z)
  21070. var shortest = Number.MAX_VALUE; // init distance vars
  21071. var tmpDistance = shortest;
  21072. var fib; // current facet in the block
  21073. var norm; // current facet normal
  21074. var p0; // current facet barycenter position
  21075. // loop on all the facets in the current partitioning block
  21076. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21077. fib = facetsInBlock[idx];
  21078. norm = facetNormals[fib];
  21079. p0 = facetPositions[fib];
  21080. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21081. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21082. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21083. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21084. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21085. projx = x + norm.x * t0;
  21086. projy = y + norm.y * t0;
  21087. projz = z + norm.z * t0;
  21088. tmpx = projx - x;
  21089. tmpy = projy - y;
  21090. tmpz = projz - z;
  21091. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21092. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21093. shortest = tmpDistance;
  21094. closest = fib;
  21095. if (projected) {
  21096. projected.x = projx;
  21097. projected.y = projy;
  21098. projected.z = projz;
  21099. }
  21100. }
  21101. }
  21102. }
  21103. return closest;
  21104. };
  21105. /**
  21106. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21107. * @returns the parameters
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.getFacetDataParameters = function () {
  21111. return this._facetParameters;
  21112. };
  21113. /**
  21114. * Disables the feature FacetData and frees the related memory
  21115. * @returns the current mesh
  21116. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21117. */
  21118. AbstractMesh.prototype.disableFacetData = function () {
  21119. if (this._facetDataEnabled) {
  21120. this._facetDataEnabled = false;
  21121. this._facetPositions = new Array();
  21122. this._facetNormals = new Array();
  21123. this._facetPartitioning = new Array();
  21124. this._facetParameters = null;
  21125. this._depthSortedIndices = new Uint32Array(0);
  21126. }
  21127. return this;
  21128. };
  21129. /**
  21130. * Updates the AbstractMesh indices array
  21131. * @param indices defines the data source
  21132. * @returns the current mesh
  21133. */
  21134. AbstractMesh.prototype.updateIndices = function (indices) {
  21135. return this;
  21136. };
  21137. /**
  21138. * Creates new normals data for the mesh
  21139. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21140. * @returns the current mesh
  21141. */
  21142. AbstractMesh.prototype.createNormals = function (updatable) {
  21143. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21144. var indices = this.getIndices();
  21145. var normals;
  21146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21147. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21148. }
  21149. else {
  21150. normals = [];
  21151. }
  21152. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21153. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21154. return this;
  21155. };
  21156. /**
  21157. * Align the mesh with a normal
  21158. * @param normal defines the normal to use
  21159. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21160. * @returns the current mesh
  21161. */
  21162. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21163. if (!upDirection) {
  21164. upDirection = BABYLON.Axis.Y;
  21165. }
  21166. var axisX = BABYLON.Tmp.Vector3[0];
  21167. var axisZ = BABYLON.Tmp.Vector3[1];
  21168. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21169. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21170. if (this.rotationQuaternion) {
  21171. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21172. }
  21173. else {
  21174. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21175. }
  21176. return this;
  21177. };
  21178. /** @hidden */
  21179. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21180. var engine = this.getEngine();
  21181. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21182. this._isOccluded = false;
  21183. return;
  21184. }
  21185. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21186. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21187. if (isOcclusionQueryAvailable) {
  21188. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21189. this._isOcclusionQueryInProgress = false;
  21190. this._occlusionInternalRetryCounter = 0;
  21191. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21192. }
  21193. else {
  21194. this._occlusionInternalRetryCounter++;
  21195. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21196. this._isOcclusionQueryInProgress = false;
  21197. this._occlusionInternalRetryCounter = 0;
  21198. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21199. // if strict continue the last state of the object.
  21200. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21201. }
  21202. else {
  21203. return;
  21204. }
  21205. }
  21206. }
  21207. var scene = this.getScene();
  21208. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21209. if (!this._occlusionQuery) {
  21210. this._occlusionQuery = engine.createQuery();
  21211. }
  21212. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21213. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21214. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21215. this._isOcclusionQueryInProgress = true;
  21216. };
  21217. /** No occlusion */
  21218. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21219. /** Occlusion set to optimisitic */
  21220. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21221. /** Occlusion set to strict */
  21222. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21223. /** Use an accurante occlusion algorithm */
  21224. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21225. /** Use a conservative occlusion algorithm */
  21226. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21227. return AbstractMesh;
  21228. }(BABYLON.TransformNode));
  21229. BABYLON.AbstractMesh = AbstractMesh;
  21230. })(BABYLON || (BABYLON = {}));
  21231. //# sourceMappingURL=babylon.abstractMesh.js.map
  21232. var BABYLON;
  21233. (function (BABYLON) {
  21234. /**
  21235. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21236. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21237. * 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.
  21238. */
  21239. var Light = /** @class */ (function (_super) {
  21240. __extends(Light, _super);
  21241. /**
  21242. * Creates a Light object in the scene.
  21243. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21244. * @param name The firendly name of the light
  21245. * @param scene The scene the light belongs too
  21246. */
  21247. function Light(name, scene) {
  21248. var _this = _super.call(this, name, scene) || this;
  21249. /**
  21250. * Diffuse gives the basic color to an object.
  21251. */
  21252. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21253. /**
  21254. * Specular produces a highlight color on an object.
  21255. * Note: This is note affecting PBR materials.
  21256. */
  21257. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21258. /**
  21259. * Strength of the light.
  21260. * Note: By default it is define in the framework own unit.
  21261. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21262. */
  21263. _this.intensity = 1.0;
  21264. /**
  21265. * Defines how far from the source the light is impacting in scene units.
  21266. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21267. */
  21268. _this.range = Number.MAX_VALUE;
  21269. /**
  21270. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21271. * of light.
  21272. */
  21273. _this._photometricScale = 1.0;
  21274. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21275. _this._radius = 0.00001;
  21276. /**
  21277. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21278. * exceeding the number allowed of the materials.
  21279. */
  21280. _this.renderPriority = 0;
  21281. /**
  21282. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21283. * the current shadow generator.
  21284. */
  21285. _this.shadowEnabled = true;
  21286. _this._excludeWithLayerMask = 0;
  21287. _this._includeOnlyWithLayerMask = 0;
  21288. _this._lightmapMode = 0;
  21289. /**
  21290. * @hidden Internal use only.
  21291. */
  21292. _this._excludedMeshesIds = new Array();
  21293. /**
  21294. * @hidden Internal use only.
  21295. */
  21296. _this._includedOnlyMeshesIds = new Array();
  21297. _this.getScene().addLight(_this);
  21298. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21299. _this._buildUniformLayout();
  21300. _this.includedOnlyMeshes = new Array();
  21301. _this.excludedMeshes = new Array();
  21302. _this._resyncMeshes();
  21303. return _this;
  21304. }
  21305. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21306. /**
  21307. * If every light affecting the material is in this lightmapMode,
  21308. * material.lightmapTexture adds or multiplies
  21309. * (depends on material.useLightmapAsShadowmap)
  21310. * after every other light calculations.
  21311. */
  21312. get: function () {
  21313. return Light._LIGHTMAP_DEFAULT;
  21314. },
  21315. enumerable: true,
  21316. configurable: true
  21317. });
  21318. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21319. /**
  21320. * material.lightmapTexture as only diffuse lighting from this light
  21321. * adds only specular lighting from this light
  21322. * adds dynamic shadows
  21323. */
  21324. get: function () {
  21325. return Light._LIGHTMAP_SPECULAR;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21331. /**
  21332. * material.lightmapTexture as only lighting
  21333. * no light calculation from this light
  21334. * only adds dynamic shadows from this light
  21335. */
  21336. get: function () {
  21337. return Light._LIGHTMAP_SHADOWSONLY;
  21338. },
  21339. enumerable: true,
  21340. configurable: true
  21341. });
  21342. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21343. /**
  21344. * Each light type uses the default quantity according to its type:
  21345. * point/spot lights use luminous intensity
  21346. * directional lights use illuminance
  21347. */
  21348. get: function () {
  21349. return Light._INTENSITYMODE_AUTOMATIC;
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21355. /**
  21356. * lumen (lm)
  21357. */
  21358. get: function () {
  21359. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21365. /**
  21366. * candela (lm/sr)
  21367. */
  21368. get: function () {
  21369. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21370. },
  21371. enumerable: true,
  21372. configurable: true
  21373. });
  21374. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21375. /**
  21376. * lux (lm/m^2)
  21377. */
  21378. get: function () {
  21379. return Light._INTENSITYMODE_ILLUMINANCE;
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21385. /**
  21386. * nit (cd/m^2)
  21387. */
  21388. get: function () {
  21389. return Light._INTENSITYMODE_LUMINANCE;
  21390. },
  21391. enumerable: true,
  21392. configurable: true
  21393. });
  21394. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21395. /**
  21396. * Light type const id of the point light.
  21397. */
  21398. get: function () {
  21399. return Light._LIGHTTYPEID_POINTLIGHT;
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21405. /**
  21406. * Light type const id of the directional light.
  21407. */
  21408. get: function () {
  21409. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21410. },
  21411. enumerable: true,
  21412. configurable: true
  21413. });
  21414. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21415. /**
  21416. * Light type const id of the spot light.
  21417. */
  21418. get: function () {
  21419. return Light._LIGHTTYPEID_SPOTLIGHT;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21425. /**
  21426. * Light type const id of the hemispheric light.
  21427. */
  21428. get: function () {
  21429. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. Object.defineProperty(Light.prototype, "intensityMode", {
  21435. /**
  21436. * Gets the photometric scale used to interpret the intensity.
  21437. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21438. */
  21439. get: function () {
  21440. return this._intensityMode;
  21441. },
  21442. /**
  21443. * Sets the photometric scale used to interpret the intensity.
  21444. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21445. */
  21446. set: function (value) {
  21447. this._intensityMode = value;
  21448. this._computePhotometricScale();
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. ;
  21454. ;
  21455. Object.defineProperty(Light.prototype, "radius", {
  21456. /**
  21457. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21458. */
  21459. get: function () {
  21460. return this._radius;
  21461. },
  21462. /**
  21463. * sets the light radius used by PBR Materials to simulate soft area lights.
  21464. */
  21465. set: function (value) {
  21466. this._radius = value;
  21467. this._computePhotometricScale();
  21468. },
  21469. enumerable: true,
  21470. configurable: true
  21471. });
  21472. ;
  21473. ;
  21474. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21475. /**
  21476. * Gets the only meshes impacted by this light.
  21477. */
  21478. get: function () {
  21479. return this._includedOnlyMeshes;
  21480. },
  21481. /**
  21482. * Sets the only meshes impacted by this light.
  21483. */
  21484. set: function (value) {
  21485. this._includedOnlyMeshes = value;
  21486. this._hookArrayForIncludedOnly(value);
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21492. /**
  21493. * Gets the meshes not impacted by this light.
  21494. */
  21495. get: function () {
  21496. return this._excludedMeshes;
  21497. },
  21498. /**
  21499. * Sets the meshes not impacted by this light.
  21500. */
  21501. set: function (value) {
  21502. this._excludedMeshes = value;
  21503. this._hookArrayForExcluded(value);
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21509. /**
  21510. * Gets the layer id use to find what meshes are not impacted by the light.
  21511. * Inactive if 0
  21512. */
  21513. get: function () {
  21514. return this._excludeWithLayerMask;
  21515. },
  21516. /**
  21517. * Sets the layer id use to find what meshes are not impacted by the light.
  21518. * Inactive if 0
  21519. */
  21520. set: function (value) {
  21521. this._excludeWithLayerMask = value;
  21522. this._resyncMeshes();
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21528. /**
  21529. * Gets the layer id use to find what meshes are impacted by the light.
  21530. * Inactive if 0
  21531. */
  21532. get: function () {
  21533. return this._includeOnlyWithLayerMask;
  21534. },
  21535. /**
  21536. * Sets the layer id use to find what meshes are impacted by the light.
  21537. * Inactive if 0
  21538. */
  21539. set: function (value) {
  21540. this._includeOnlyWithLayerMask = value;
  21541. this._resyncMeshes();
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. Object.defineProperty(Light.prototype, "lightmapMode", {
  21547. /**
  21548. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21549. */
  21550. get: function () {
  21551. return this._lightmapMode;
  21552. },
  21553. /**
  21554. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21555. */
  21556. set: function (value) {
  21557. if (this._lightmapMode === value) {
  21558. return;
  21559. }
  21560. this._lightmapMode = value;
  21561. this._markMeshesAsLightDirty();
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. /**
  21567. * Returns the string "Light".
  21568. * @returns the class name
  21569. */
  21570. Light.prototype.getClassName = function () {
  21571. return "Light";
  21572. };
  21573. /**
  21574. * Converts the light information to a readable string for debug purpose.
  21575. * @param fullDetails Supports for multiple levels of logging within scene loading
  21576. * @returns the human readable light info
  21577. */
  21578. Light.prototype.toString = function (fullDetails) {
  21579. var ret = "Name: " + this.name;
  21580. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21581. if (this.animations) {
  21582. for (var i = 0; i < this.animations.length; i++) {
  21583. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21584. }
  21585. }
  21586. if (fullDetails) {
  21587. }
  21588. return ret;
  21589. };
  21590. /**
  21591. * Set the enabled state of this node.
  21592. * @param value - the new enabled state
  21593. */
  21594. Light.prototype.setEnabled = function (value) {
  21595. _super.prototype.setEnabled.call(this, value);
  21596. this._resyncMeshes();
  21597. };
  21598. /**
  21599. * Returns the Light associated shadow generator if any.
  21600. * @return the associated shadow generator.
  21601. */
  21602. Light.prototype.getShadowGenerator = function () {
  21603. return this._shadowGenerator;
  21604. };
  21605. /**
  21606. * Returns a Vector3, the absolute light position in the World.
  21607. * @returns the world space position of the light
  21608. */
  21609. Light.prototype.getAbsolutePosition = function () {
  21610. return BABYLON.Vector3.Zero();
  21611. };
  21612. /**
  21613. * Specifies if the light will affect the passed mesh.
  21614. * @param mesh The mesh to test against the light
  21615. * @return true the mesh is affected otherwise, false.
  21616. */
  21617. Light.prototype.canAffectMesh = function (mesh) {
  21618. if (!mesh) {
  21619. return true;
  21620. }
  21621. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21622. return false;
  21623. }
  21624. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21625. return false;
  21626. }
  21627. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21628. return false;
  21629. }
  21630. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21631. return false;
  21632. }
  21633. return true;
  21634. };
  21635. /**
  21636. * Computes and Returns the light World matrix.
  21637. * @returns the world matrix
  21638. */
  21639. Light.prototype.getWorldMatrix = function () {
  21640. this._currentRenderId = this.getScene().getRenderId();
  21641. this._childRenderId = this._currentRenderId;
  21642. var worldMatrix = this._getWorldMatrix();
  21643. if (this.parent && this.parent.getWorldMatrix) {
  21644. if (!this._parentedWorldMatrix) {
  21645. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21646. }
  21647. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21648. this._markSyncedWithParent();
  21649. return this._parentedWorldMatrix;
  21650. }
  21651. return worldMatrix;
  21652. };
  21653. /**
  21654. * Sort function to order lights for rendering.
  21655. * @param a First Light object to compare to second.
  21656. * @param b Second Light object to compare first.
  21657. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21658. */
  21659. Light.CompareLightsPriority = function (a, b) {
  21660. //shadow-casting lights have priority over non-shadow-casting lights
  21661. //the renderPrioirty is a secondary sort criterion
  21662. if (a.shadowEnabled !== b.shadowEnabled) {
  21663. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21664. }
  21665. return b.renderPriority - a.renderPriority;
  21666. };
  21667. /**
  21668. * Releases resources associated with this node.
  21669. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21670. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21671. */
  21672. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21673. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21674. if (this._shadowGenerator) {
  21675. this._shadowGenerator.dispose();
  21676. this._shadowGenerator = null;
  21677. }
  21678. // Animations
  21679. this.getScene().stopAnimation(this);
  21680. // Remove from meshes
  21681. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21682. var mesh = _a[_i];
  21683. mesh._removeLightSource(this);
  21684. }
  21685. this._uniformBuffer.dispose();
  21686. // Remove from scene
  21687. this.getScene().removeLight(this);
  21688. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21689. };
  21690. /**
  21691. * Returns the light type ID (integer).
  21692. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21693. */
  21694. Light.prototype.getTypeID = function () {
  21695. return 0;
  21696. };
  21697. /**
  21698. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21699. * @returns the scaled intensity in intensity mode unit
  21700. */
  21701. Light.prototype.getScaledIntensity = function () {
  21702. return this._photometricScale * this.intensity;
  21703. };
  21704. /**
  21705. * Returns a new Light object, named "name", from the current one.
  21706. * @param name The name of the cloned light
  21707. * @returns the new created light
  21708. */
  21709. Light.prototype.clone = function (name) {
  21710. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21711. if (!constructor) {
  21712. return null;
  21713. }
  21714. return BABYLON.SerializationHelper.Clone(constructor, this);
  21715. };
  21716. /**
  21717. * Serializes the current light into a Serialization object.
  21718. * @returns the serialized object.
  21719. */
  21720. Light.prototype.serialize = function () {
  21721. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21722. // Type
  21723. serializationObject.type = this.getTypeID();
  21724. // Parent
  21725. if (this.parent) {
  21726. serializationObject.parentId = this.parent.id;
  21727. }
  21728. // Inclusion / exclusions
  21729. if (this.excludedMeshes.length > 0) {
  21730. serializationObject.excludedMeshesIds = [];
  21731. this.excludedMeshes.forEach(function (mesh) {
  21732. serializationObject.excludedMeshesIds.push(mesh.id);
  21733. });
  21734. }
  21735. if (this.includedOnlyMeshes.length > 0) {
  21736. serializationObject.includedOnlyMeshesIds = [];
  21737. this.includedOnlyMeshes.forEach(function (mesh) {
  21738. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21739. });
  21740. }
  21741. // Animations
  21742. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21743. serializationObject.ranges = this.serializeAnimationRanges();
  21744. return serializationObject;
  21745. };
  21746. /**
  21747. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21748. * This new light is named "name" and added to the passed scene.
  21749. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21750. * @param name The friendly name of the light
  21751. * @param scene The scene the new light will belong to
  21752. * @returns the constructor function
  21753. */
  21754. Light.GetConstructorFromName = function (type, name, scene) {
  21755. switch (type) {
  21756. case 0:
  21757. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21758. case 1:
  21759. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21760. case 2:
  21761. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21762. case 3:
  21763. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21764. }
  21765. return null;
  21766. };
  21767. /**
  21768. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21769. * @param parsedLight The JSON representation of the light
  21770. * @param scene The scene to create the parsed light in
  21771. * @returns the created light after parsing
  21772. */
  21773. Light.Parse = function (parsedLight, scene) {
  21774. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21775. if (!constructor) {
  21776. return null;
  21777. }
  21778. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21779. // Inclusion / exclusions
  21780. if (parsedLight.excludedMeshesIds) {
  21781. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21782. }
  21783. if (parsedLight.includedOnlyMeshesIds) {
  21784. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21785. }
  21786. // Parent
  21787. if (parsedLight.parentId) {
  21788. light._waitingParentId = parsedLight.parentId;
  21789. }
  21790. // Animations
  21791. if (parsedLight.animations) {
  21792. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21793. var parsedAnimation = parsedLight.animations[animationIndex];
  21794. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21795. }
  21796. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21797. }
  21798. if (parsedLight.autoAnimate) {
  21799. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21800. }
  21801. return light;
  21802. };
  21803. Light.prototype._hookArrayForExcluded = function (array) {
  21804. var _this = this;
  21805. var oldPush = array.push;
  21806. array.push = function () {
  21807. var items = [];
  21808. for (var _i = 0; _i < arguments.length; _i++) {
  21809. items[_i] = arguments[_i];
  21810. }
  21811. var result = oldPush.apply(array, items);
  21812. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21813. var item = items_1[_a];
  21814. item._resyncLighSource(_this);
  21815. }
  21816. return result;
  21817. };
  21818. var oldSplice = array.splice;
  21819. array.splice = function (index, deleteCount) {
  21820. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21821. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21822. var item = deleted_1[_i];
  21823. item._resyncLighSource(_this);
  21824. }
  21825. return deleted;
  21826. };
  21827. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21828. var item = array_1[_i];
  21829. item._resyncLighSource(this);
  21830. }
  21831. };
  21832. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21833. var _this = this;
  21834. var oldPush = array.push;
  21835. array.push = function () {
  21836. var items = [];
  21837. for (var _i = 0; _i < arguments.length; _i++) {
  21838. items[_i] = arguments[_i];
  21839. }
  21840. var result = oldPush.apply(array, items);
  21841. _this._resyncMeshes();
  21842. return result;
  21843. };
  21844. var oldSplice = array.splice;
  21845. array.splice = function (index, deleteCount) {
  21846. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21847. _this._resyncMeshes();
  21848. return deleted;
  21849. };
  21850. this._resyncMeshes();
  21851. };
  21852. Light.prototype._resyncMeshes = function () {
  21853. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21854. var mesh = _a[_i];
  21855. mesh._resyncLighSource(this);
  21856. }
  21857. };
  21858. /**
  21859. * Forces the meshes to update their light related information in their rendering used effects
  21860. * @hidden Internal Use Only
  21861. */
  21862. Light.prototype._markMeshesAsLightDirty = function () {
  21863. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21864. var mesh = _a[_i];
  21865. if (mesh._lightSources.indexOf(this) !== -1) {
  21866. mesh._markSubMeshesAsLightDirty();
  21867. }
  21868. }
  21869. };
  21870. /**
  21871. * Recomputes the cached photometric scale if needed.
  21872. */
  21873. Light.prototype._computePhotometricScale = function () {
  21874. this._photometricScale = this._getPhotometricScale();
  21875. this.getScene().resetCachedMaterial();
  21876. };
  21877. /**
  21878. * Returns the Photometric Scale according to the light type and intensity mode.
  21879. */
  21880. Light.prototype._getPhotometricScale = function () {
  21881. var photometricScale = 0.0;
  21882. var lightTypeID = this.getTypeID();
  21883. //get photometric mode
  21884. var photometricMode = this.intensityMode;
  21885. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21886. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21887. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21888. }
  21889. else {
  21890. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21891. }
  21892. }
  21893. //compute photometric scale
  21894. switch (lightTypeID) {
  21895. case Light.LIGHTTYPEID_POINTLIGHT:
  21896. case Light.LIGHTTYPEID_SPOTLIGHT:
  21897. switch (photometricMode) {
  21898. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21899. photometricScale = 1.0 / (4.0 * Math.PI);
  21900. break;
  21901. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21902. photometricScale = 1.0;
  21903. break;
  21904. case Light.INTENSITYMODE_LUMINANCE:
  21905. photometricScale = this.radius * this.radius;
  21906. break;
  21907. }
  21908. break;
  21909. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21910. switch (photometricMode) {
  21911. case Light.INTENSITYMODE_ILLUMINANCE:
  21912. photometricScale = 1.0;
  21913. break;
  21914. case Light.INTENSITYMODE_LUMINANCE:
  21915. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21916. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21917. var apexAngleRadians = this.radius;
  21918. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21919. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21920. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21921. photometricScale = solidAngle;
  21922. break;
  21923. }
  21924. break;
  21925. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21926. // No fall off in hemisperic light.
  21927. photometricScale = 1.0;
  21928. break;
  21929. }
  21930. return photometricScale;
  21931. };
  21932. /**
  21933. * Reorder the light in the scene according to their defined priority.
  21934. * @hidden Internal Use Only
  21935. */
  21936. Light.prototype._reorderLightsInScene = function () {
  21937. var scene = this.getScene();
  21938. if (this._renderPriority != 0) {
  21939. scene.requireLightSorting = true;
  21940. }
  21941. this.getScene().sortLightsByPriority();
  21942. };
  21943. //lightmapMode Consts
  21944. Light._LIGHTMAP_DEFAULT = 0;
  21945. Light._LIGHTMAP_SPECULAR = 1;
  21946. Light._LIGHTMAP_SHADOWSONLY = 2;
  21947. // Intensity Mode Consts
  21948. Light._INTENSITYMODE_AUTOMATIC = 0;
  21949. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21950. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21951. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21952. Light._INTENSITYMODE_LUMINANCE = 4;
  21953. // Light types ids const.
  21954. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21955. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21956. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21957. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21958. __decorate([
  21959. BABYLON.serializeAsColor3()
  21960. ], Light.prototype, "diffuse", void 0);
  21961. __decorate([
  21962. BABYLON.serializeAsColor3()
  21963. ], Light.prototype, "specular", void 0);
  21964. __decorate([
  21965. BABYLON.serialize()
  21966. ], Light.prototype, "intensity", void 0);
  21967. __decorate([
  21968. BABYLON.serialize()
  21969. ], Light.prototype, "range", void 0);
  21970. __decorate([
  21971. BABYLON.serialize()
  21972. ], Light.prototype, "intensityMode", null);
  21973. __decorate([
  21974. BABYLON.serialize()
  21975. ], Light.prototype, "radius", null);
  21976. __decorate([
  21977. BABYLON.serialize()
  21978. ], Light.prototype, "_renderPriority", void 0);
  21979. __decorate([
  21980. BABYLON.expandToProperty("_reorderLightsInScene")
  21981. ], Light.prototype, "renderPriority", void 0);
  21982. __decorate([
  21983. BABYLON.serialize()
  21984. ], Light.prototype, "shadowEnabled", void 0);
  21985. __decorate([
  21986. BABYLON.serialize("excludeWithLayerMask")
  21987. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21988. __decorate([
  21989. BABYLON.serialize("includeOnlyWithLayerMask")
  21990. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21991. __decorate([
  21992. BABYLON.serialize("lightmapMode")
  21993. ], Light.prototype, "_lightmapMode", void 0);
  21994. return Light;
  21995. }(BABYLON.Node));
  21996. BABYLON.Light = Light;
  21997. })(BABYLON || (BABYLON = {}));
  21998. //# sourceMappingURL=babylon.light.js.map
  21999. var BABYLON;
  22000. (function (BABYLON) {
  22001. var Camera = /** @class */ (function (_super) {
  22002. __extends(Camera, _super);
  22003. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22004. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22005. var _this = _super.call(this, name, scene) || this;
  22006. /**
  22007. * The vector the camera should consider as up.
  22008. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22009. */
  22010. _this.upVector = BABYLON.Vector3.Up();
  22011. _this.orthoLeft = null;
  22012. _this.orthoRight = null;
  22013. _this.orthoBottom = null;
  22014. _this.orthoTop = null;
  22015. /**
  22016. * FOV is set in Radians. (default is 0.8)
  22017. */
  22018. _this.fov = 0.8;
  22019. _this.minZ = 1;
  22020. _this.maxZ = 10000.0;
  22021. _this.inertia = 0.9;
  22022. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22023. _this.isIntermediate = false;
  22024. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22025. /**
  22026. * Restricts the camera to viewing objects with the same layerMask.
  22027. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22028. */
  22029. _this.layerMask = 0x0FFFFFFF;
  22030. /**
  22031. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22032. */
  22033. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22034. // Camera rig members
  22035. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22036. _this._rigCameras = new Array();
  22037. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22038. _this._skipRendering = false;
  22039. _this.customRenderTargets = new Array();
  22040. // Observables
  22041. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22042. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22043. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22044. _this.onRestoreStateObservable = new BABYLON.Observable();
  22045. // Cache
  22046. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22047. _this._projectionMatrix = new BABYLON.Matrix();
  22048. _this._doNotComputeProjectionMatrix = false;
  22049. _this._worldMatrix = BABYLON.Matrix.Identity();
  22050. _this._postProcesses = new Array();
  22051. _this._transformMatrix = BABYLON.Matrix.Zero();
  22052. _this._activeMeshes = new BABYLON.SmartArray(256);
  22053. _this._globalPosition = BABYLON.Vector3.Zero();
  22054. _this._refreshFrustumPlanes = true;
  22055. _this.getScene().addCamera(_this);
  22056. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22057. _this.getScene().activeCamera = _this;
  22058. }
  22059. _this.position = position;
  22060. return _this;
  22061. }
  22062. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22063. get: function () {
  22064. return Camera._PERSPECTIVE_CAMERA;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22070. get: function () {
  22071. return Camera._ORTHOGRAPHIC_CAMERA;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22077. /**
  22078. * This is the default FOV mode for perspective cameras.
  22079. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22080. *
  22081. */
  22082. get: function () {
  22083. return Camera._FOVMODE_VERTICAL_FIXED;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22089. /**
  22090. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22091. *
  22092. */
  22093. get: function () {
  22094. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22100. get: function () {
  22101. return Camera._RIG_MODE_NONE;
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22107. get: function () {
  22108. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22114. get: function () {
  22115. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22116. },
  22117. enumerable: true,
  22118. configurable: true
  22119. });
  22120. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22121. get: function () {
  22122. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22123. },
  22124. enumerable: true,
  22125. configurable: true
  22126. });
  22127. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22128. get: function () {
  22129. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22135. get: function () {
  22136. return Camera._RIG_MODE_VR;
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22142. get: function () {
  22143. return Camera._RIG_MODE_WEBVR;
  22144. },
  22145. enumerable: true,
  22146. configurable: true
  22147. });
  22148. /**
  22149. * Store current camera state (fov, position, etc..)
  22150. */
  22151. Camera.prototype.storeState = function () {
  22152. this._stateStored = true;
  22153. this._storedFov = this.fov;
  22154. return this;
  22155. };
  22156. /**
  22157. * Restores the camera state values if it has been stored. You must call storeState() first
  22158. */
  22159. Camera.prototype._restoreStateValues = function () {
  22160. if (!this._stateStored) {
  22161. return false;
  22162. }
  22163. this.fov = this._storedFov;
  22164. return true;
  22165. };
  22166. /**
  22167. * Restored camera state. You must call storeState() first
  22168. */
  22169. Camera.prototype.restoreState = function () {
  22170. if (this._restoreStateValues()) {
  22171. this.onRestoreStateObservable.notifyObservers(this);
  22172. return true;
  22173. }
  22174. return false;
  22175. };
  22176. Camera.prototype.getClassName = function () {
  22177. return "Camera";
  22178. };
  22179. /**
  22180. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22181. */
  22182. Camera.prototype.toString = function (fullDetails) {
  22183. var ret = "Name: " + this.name;
  22184. ret += ", type: " + this.getClassName();
  22185. if (this.animations) {
  22186. for (var i = 0; i < this.animations.length; i++) {
  22187. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22188. }
  22189. }
  22190. if (fullDetails) {
  22191. }
  22192. return ret;
  22193. };
  22194. Object.defineProperty(Camera.prototype, "globalPosition", {
  22195. get: function () {
  22196. return this._globalPosition;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Camera.prototype.getActiveMeshes = function () {
  22202. return this._activeMeshes;
  22203. };
  22204. Camera.prototype.isActiveMesh = function (mesh) {
  22205. return (this._activeMeshes.indexOf(mesh) !== -1);
  22206. };
  22207. /**
  22208. * Is this camera ready to be used/rendered
  22209. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22210. * @return true if the camera is ready
  22211. */
  22212. Camera.prototype.isReady = function (completeCheck) {
  22213. if (completeCheck === void 0) { completeCheck = false; }
  22214. if (completeCheck) {
  22215. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22216. var pp = _a[_i];
  22217. if (pp && !pp.isReady()) {
  22218. return false;
  22219. }
  22220. }
  22221. }
  22222. return _super.prototype.isReady.call(this, completeCheck);
  22223. };
  22224. //Cache
  22225. Camera.prototype._initCache = function () {
  22226. _super.prototype._initCache.call(this);
  22227. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22228. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22229. this._cache.mode = undefined;
  22230. this._cache.minZ = undefined;
  22231. this._cache.maxZ = undefined;
  22232. this._cache.fov = undefined;
  22233. this._cache.fovMode = undefined;
  22234. this._cache.aspectRatio = undefined;
  22235. this._cache.orthoLeft = undefined;
  22236. this._cache.orthoRight = undefined;
  22237. this._cache.orthoBottom = undefined;
  22238. this._cache.orthoTop = undefined;
  22239. this._cache.renderWidth = undefined;
  22240. this._cache.renderHeight = undefined;
  22241. };
  22242. Camera.prototype._updateCache = function (ignoreParentClass) {
  22243. if (!ignoreParentClass) {
  22244. _super.prototype._updateCache.call(this);
  22245. }
  22246. this._cache.position.copyFrom(this.position);
  22247. this._cache.upVector.copyFrom(this.upVector);
  22248. };
  22249. // Synchronized
  22250. Camera.prototype._isSynchronized = function () {
  22251. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22252. };
  22253. Camera.prototype._isSynchronizedViewMatrix = function () {
  22254. if (!_super.prototype._isSynchronized.call(this))
  22255. return false;
  22256. return this._cache.position.equals(this.position)
  22257. && this._cache.upVector.equals(this.upVector)
  22258. && this.isSynchronizedWithParent();
  22259. };
  22260. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22261. var check = this._cache.mode === this.mode
  22262. && this._cache.minZ === this.minZ
  22263. && this._cache.maxZ === this.maxZ;
  22264. if (!check) {
  22265. return false;
  22266. }
  22267. var engine = this.getEngine();
  22268. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22269. check = this._cache.fov === this.fov
  22270. && this._cache.fovMode === this.fovMode
  22271. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22272. }
  22273. else {
  22274. check = this._cache.orthoLeft === this.orthoLeft
  22275. && this._cache.orthoRight === this.orthoRight
  22276. && this._cache.orthoBottom === this.orthoBottom
  22277. && this._cache.orthoTop === this.orthoTop
  22278. && this._cache.renderWidth === engine.getRenderWidth()
  22279. && this._cache.renderHeight === engine.getRenderHeight();
  22280. }
  22281. return check;
  22282. };
  22283. // Controls
  22284. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22285. };
  22286. Camera.prototype.detachControl = function (element) {
  22287. };
  22288. Camera.prototype.update = function () {
  22289. this._checkInputs();
  22290. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22291. this._updateRigCameras();
  22292. }
  22293. };
  22294. Camera.prototype._checkInputs = function () {
  22295. this.onAfterCheckInputsObservable.notifyObservers(this);
  22296. };
  22297. Object.defineProperty(Camera.prototype, "rigCameras", {
  22298. get: function () {
  22299. return this._rigCameras;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22305. get: function () {
  22306. return this._rigPostProcess;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. /**
  22312. * Internal, gets the first post proces.
  22313. * @returns the first post process to be run on this camera.
  22314. */
  22315. Camera.prototype._getFirstPostProcess = function () {
  22316. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22317. if (this._postProcesses[ppIndex] !== null) {
  22318. return this._postProcesses[ppIndex];
  22319. }
  22320. }
  22321. return null;
  22322. };
  22323. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22324. // invalidate framebuffer
  22325. var firstPostProcess = this._getFirstPostProcess();
  22326. if (firstPostProcess) {
  22327. firstPostProcess.markTextureDirty();
  22328. }
  22329. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22330. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22331. var cam = this._rigCameras[i];
  22332. var rigPostProcess = cam._rigPostProcess;
  22333. // for VR rig, there does not have to be a post process
  22334. if (rigPostProcess) {
  22335. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22336. if (isPass) {
  22337. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22338. cam.isIntermediate = this._postProcesses.length === 0;
  22339. }
  22340. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22341. rigPostProcess.markTextureDirty();
  22342. }
  22343. else {
  22344. cam._postProcesses = this._postProcesses.slice(0);
  22345. }
  22346. }
  22347. };
  22348. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22349. if (insertAt === void 0) { insertAt = null; }
  22350. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22351. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22352. return 0;
  22353. }
  22354. if (insertAt == null || insertAt < 0) {
  22355. this._postProcesses.push(postProcess);
  22356. }
  22357. else if (this._postProcesses[insertAt] === null) {
  22358. this._postProcesses[insertAt] = postProcess;
  22359. }
  22360. else {
  22361. this._postProcesses.splice(insertAt, 0, postProcess);
  22362. }
  22363. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22364. return this._postProcesses.indexOf(postProcess);
  22365. };
  22366. Camera.prototype.detachPostProcess = function (postProcess) {
  22367. var idx = this._postProcesses.indexOf(postProcess);
  22368. if (idx !== -1) {
  22369. this._postProcesses[idx] = null;
  22370. }
  22371. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22372. };
  22373. Camera.prototype.getWorldMatrix = function () {
  22374. if (this._isSynchronizedViewMatrix()) {
  22375. return this._worldMatrix;
  22376. }
  22377. // Getting the the view matrix will also compute the world matrix.
  22378. this.getViewMatrix();
  22379. return this._worldMatrix;
  22380. };
  22381. Camera.prototype._getViewMatrix = function () {
  22382. return BABYLON.Matrix.Identity();
  22383. };
  22384. Camera.prototype.getViewMatrix = function (force) {
  22385. if (!force && this._isSynchronizedViewMatrix()) {
  22386. return this._computedViewMatrix;
  22387. }
  22388. this.updateCache();
  22389. this._computedViewMatrix = this._getViewMatrix();
  22390. this._currentRenderId = this.getScene().getRenderId();
  22391. this._childRenderId = this._currentRenderId;
  22392. this._refreshFrustumPlanes = true;
  22393. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22394. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22395. }
  22396. this.onViewMatrixChangedObservable.notifyObservers(this);
  22397. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22398. return this._computedViewMatrix;
  22399. };
  22400. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22401. this._doNotComputeProjectionMatrix = true;
  22402. if (projection !== undefined) {
  22403. this._projectionMatrix = projection;
  22404. }
  22405. };
  22406. ;
  22407. Camera.prototype.unfreezeProjectionMatrix = function () {
  22408. this._doNotComputeProjectionMatrix = false;
  22409. };
  22410. ;
  22411. Camera.prototype.getProjectionMatrix = function (force) {
  22412. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22413. return this._projectionMatrix;
  22414. }
  22415. // Cache
  22416. this._cache.mode = this.mode;
  22417. this._cache.minZ = this.minZ;
  22418. this._cache.maxZ = this.maxZ;
  22419. // Matrix
  22420. this._refreshFrustumPlanes = true;
  22421. var engine = this.getEngine();
  22422. var scene = this.getScene();
  22423. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22424. this._cache.fov = this.fov;
  22425. this._cache.fovMode = this.fovMode;
  22426. this._cache.aspectRatio = engine.getAspectRatio(this);
  22427. if (this.minZ <= 0) {
  22428. this.minZ = 0.1;
  22429. }
  22430. if (scene.useRightHandedSystem) {
  22431. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22432. }
  22433. else {
  22434. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22435. }
  22436. }
  22437. else {
  22438. var halfWidth = engine.getRenderWidth() / 2.0;
  22439. var halfHeight = engine.getRenderHeight() / 2.0;
  22440. if (scene.useRightHandedSystem) {
  22441. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22442. }
  22443. else {
  22444. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22445. }
  22446. this._cache.orthoLeft = this.orthoLeft;
  22447. this._cache.orthoRight = this.orthoRight;
  22448. this._cache.orthoBottom = this.orthoBottom;
  22449. this._cache.orthoTop = this.orthoTop;
  22450. this._cache.renderWidth = engine.getRenderWidth();
  22451. this._cache.renderHeight = engine.getRenderHeight();
  22452. }
  22453. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22454. return this._projectionMatrix;
  22455. };
  22456. Camera.prototype.getTranformationMatrix = function () {
  22457. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22458. return this._transformMatrix;
  22459. };
  22460. Camera.prototype.updateFrustumPlanes = function () {
  22461. if (!this._refreshFrustumPlanes) {
  22462. return;
  22463. }
  22464. this.getTranformationMatrix();
  22465. if (!this._frustumPlanes) {
  22466. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22467. }
  22468. else {
  22469. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22470. }
  22471. this._refreshFrustumPlanes = false;
  22472. };
  22473. Camera.prototype.isInFrustum = function (target) {
  22474. this.updateFrustumPlanes();
  22475. return target.isInFrustum(this._frustumPlanes);
  22476. };
  22477. Camera.prototype.isCompletelyInFrustum = function (target) {
  22478. this.updateFrustumPlanes();
  22479. return target.isCompletelyInFrustum(this._frustumPlanes);
  22480. };
  22481. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22482. if (length === void 0) { length = 100; }
  22483. if (!transform) {
  22484. transform = this.getWorldMatrix();
  22485. }
  22486. if (!origin) {
  22487. origin = this.position;
  22488. }
  22489. var forward = new BABYLON.Vector3(0, 0, 1);
  22490. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22491. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22492. return new BABYLON.Ray(origin, direction, length);
  22493. };
  22494. /**
  22495. * Releases resources associated with this node.
  22496. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22497. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22498. */
  22499. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22500. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22501. // Observables
  22502. this.onViewMatrixChangedObservable.clear();
  22503. this.onProjectionMatrixChangedObservable.clear();
  22504. this.onAfterCheckInputsObservable.clear();
  22505. this.onRestoreStateObservable.clear();
  22506. // Inputs
  22507. if (this.inputs) {
  22508. this.inputs.clear();
  22509. }
  22510. // Animations
  22511. this.getScene().stopAnimation(this);
  22512. // Remove from scene
  22513. this.getScene().removeCamera(this);
  22514. while (this._rigCameras.length > 0) {
  22515. var camera = this._rigCameras.pop();
  22516. if (camera) {
  22517. camera.dispose();
  22518. }
  22519. }
  22520. // Postprocesses
  22521. if (this._rigPostProcess) {
  22522. this._rigPostProcess.dispose(this);
  22523. this._rigPostProcess = null;
  22524. this._postProcesses = [];
  22525. }
  22526. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22527. this._rigPostProcess = null;
  22528. this._postProcesses = [];
  22529. }
  22530. else {
  22531. var i = this._postProcesses.length;
  22532. while (--i >= 0) {
  22533. var postProcess = this._postProcesses[i];
  22534. if (postProcess) {
  22535. postProcess.dispose(this);
  22536. }
  22537. }
  22538. }
  22539. // Render targets
  22540. var i = this.customRenderTargets.length;
  22541. while (--i >= 0) {
  22542. this.customRenderTargets[i].dispose();
  22543. }
  22544. this.customRenderTargets = [];
  22545. // Active Meshes
  22546. this._activeMeshes.dispose();
  22547. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22548. };
  22549. Object.defineProperty(Camera.prototype, "leftCamera", {
  22550. // ---- Camera rigs section ----
  22551. get: function () {
  22552. if (this._rigCameras.length < 1) {
  22553. return null;
  22554. }
  22555. return this._rigCameras[0];
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. Object.defineProperty(Camera.prototype, "rightCamera", {
  22561. get: function () {
  22562. if (this._rigCameras.length < 2) {
  22563. return null;
  22564. }
  22565. return this._rigCameras[1];
  22566. },
  22567. enumerable: true,
  22568. configurable: true
  22569. });
  22570. Camera.prototype.getLeftTarget = function () {
  22571. if (this._rigCameras.length < 1) {
  22572. return null;
  22573. }
  22574. return this._rigCameras[0].getTarget();
  22575. };
  22576. Camera.prototype.getRightTarget = function () {
  22577. if (this._rigCameras.length < 2) {
  22578. return null;
  22579. }
  22580. return this._rigCameras[1].getTarget();
  22581. };
  22582. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22583. if (this.cameraRigMode === mode) {
  22584. return;
  22585. }
  22586. while (this._rigCameras.length > 0) {
  22587. var camera = this._rigCameras.pop();
  22588. if (camera) {
  22589. camera.dispose();
  22590. }
  22591. }
  22592. this.cameraRigMode = mode;
  22593. this._cameraRigParams = {};
  22594. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22595. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22596. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22597. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22598. // create the rig cameras, unless none
  22599. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22600. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22601. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22602. if (leftCamera && rightCamera) {
  22603. this._rigCameras.push(leftCamera);
  22604. this._rigCameras.push(rightCamera);
  22605. }
  22606. }
  22607. switch (this.cameraRigMode) {
  22608. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22609. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22610. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22611. break;
  22612. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22613. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22614. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22615. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22616. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22617. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22618. break;
  22619. case Camera.RIG_MODE_VR:
  22620. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22621. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22622. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22623. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22624. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22625. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22626. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22627. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22628. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22629. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22630. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22631. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22632. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22633. if (metrics.compensateDistortion) {
  22634. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22635. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22636. }
  22637. break;
  22638. case Camera.RIG_MODE_WEBVR:
  22639. if (rigParams.vrDisplay) {
  22640. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22641. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22642. //Left eye
  22643. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22644. this._rigCameras[0].setCameraRigParameter("left", true);
  22645. //leaving this for future reference
  22646. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22647. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22648. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22649. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22650. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22651. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22652. this._rigCameras[0].parent = this;
  22653. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22654. //Right eye
  22655. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22656. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22657. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22658. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22659. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22660. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22661. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22662. this._rigCameras[1].parent = this;
  22663. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22664. if (Camera.UseAlternateWebVRRendering) {
  22665. this._rigCameras[1]._skipRendering = true;
  22666. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22667. }
  22668. }
  22669. break;
  22670. }
  22671. this._cascadePostProcessesToRigCams();
  22672. this.update();
  22673. };
  22674. Camera.prototype._getVRProjectionMatrix = function () {
  22675. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22676. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22677. return this._projectionMatrix;
  22678. };
  22679. Camera.prototype._updateCameraRotationMatrix = function () {
  22680. //Here for WebVR
  22681. };
  22682. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22683. //Here for WebVR
  22684. };
  22685. /**
  22686. * This function MUST be overwritten by the different WebVR cameras available.
  22687. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22688. */
  22689. Camera.prototype._getWebVRProjectionMatrix = function () {
  22690. return BABYLON.Matrix.Identity();
  22691. };
  22692. /**
  22693. * This function MUST be overwritten by the different WebVR cameras available.
  22694. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22695. */
  22696. Camera.prototype._getWebVRViewMatrix = function () {
  22697. return BABYLON.Matrix.Identity();
  22698. };
  22699. Camera.prototype.setCameraRigParameter = function (name, value) {
  22700. if (!this._cameraRigParams) {
  22701. this._cameraRigParams = {};
  22702. }
  22703. this._cameraRigParams[name] = value;
  22704. //provisionnally:
  22705. if (name === "interaxialDistance") {
  22706. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22707. }
  22708. };
  22709. /**
  22710. * needs to be overridden by children so sub has required properties to be copied
  22711. */
  22712. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22713. return null;
  22714. };
  22715. /**
  22716. * May need to be overridden by children
  22717. */
  22718. Camera.prototype._updateRigCameras = function () {
  22719. for (var i = 0; i < this._rigCameras.length; i++) {
  22720. this._rigCameras[i].minZ = this.minZ;
  22721. this._rigCameras[i].maxZ = this.maxZ;
  22722. this._rigCameras[i].fov = this.fov;
  22723. }
  22724. // only update viewport when ANAGLYPH
  22725. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22726. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22727. }
  22728. };
  22729. Camera.prototype._setupInputs = function () {
  22730. };
  22731. Camera.prototype.serialize = function () {
  22732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22733. // Type
  22734. serializationObject.type = this.getClassName();
  22735. // Parent
  22736. if (this.parent) {
  22737. serializationObject.parentId = this.parent.id;
  22738. }
  22739. if (this.inputs) {
  22740. this.inputs.serialize(serializationObject);
  22741. }
  22742. // Animations
  22743. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22744. serializationObject.ranges = this.serializeAnimationRanges();
  22745. return serializationObject;
  22746. };
  22747. Camera.prototype.clone = function (name) {
  22748. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22749. };
  22750. Camera.prototype.getDirection = function (localAxis) {
  22751. var result = BABYLON.Vector3.Zero();
  22752. this.getDirectionToRef(localAxis, result);
  22753. return result;
  22754. };
  22755. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22756. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22757. };
  22758. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22759. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22760. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22761. switch (type) {
  22762. case "ArcRotateCamera":
  22763. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22764. case "DeviceOrientationCamera":
  22765. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22766. case "FollowCamera":
  22767. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22768. case "ArcFollowCamera":
  22769. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22770. case "GamepadCamera":
  22771. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22772. case "TouchCamera":
  22773. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22774. case "VirtualJoysticksCamera":
  22775. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22776. case "WebVRFreeCamera":
  22777. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22778. case "WebVRGamepadCamera":
  22779. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22780. case "VRDeviceOrientationFreeCamera":
  22781. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22782. case "VRDeviceOrientationGamepadCamera":
  22783. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22784. case "AnaglyphArcRotateCamera":
  22785. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22786. case "AnaglyphFreeCamera":
  22787. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22788. case "AnaglyphGamepadCamera":
  22789. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22790. case "AnaglyphUniversalCamera":
  22791. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22792. case "StereoscopicArcRotateCamera":
  22793. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22794. case "StereoscopicFreeCamera":
  22795. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22796. case "StereoscopicGamepadCamera":
  22797. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22798. case "StereoscopicUniversalCamera":
  22799. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22800. case "FreeCamera": // Forcing Universal here
  22801. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22802. default: // Universal Camera is the default value
  22803. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22804. }
  22805. };
  22806. Camera.prototype.computeWorldMatrix = function () {
  22807. return this.getWorldMatrix();
  22808. };
  22809. Camera.Parse = function (parsedCamera, scene) {
  22810. var type = parsedCamera.type;
  22811. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22812. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22813. // Parent
  22814. if (parsedCamera.parentId) {
  22815. camera._waitingParentId = parsedCamera.parentId;
  22816. }
  22817. //If camera has an input manager, let it parse inputs settings
  22818. if (camera.inputs) {
  22819. camera.inputs.parse(parsedCamera);
  22820. camera._setupInputs();
  22821. }
  22822. if (camera.setPosition) { // need to force position
  22823. camera.position.copyFromFloats(0, 0, 0);
  22824. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22825. }
  22826. // Target
  22827. if (parsedCamera.target) {
  22828. if (camera.setTarget) {
  22829. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22830. }
  22831. }
  22832. // Apply 3d rig, when found
  22833. if (parsedCamera.cameraRigMode) {
  22834. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22835. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22836. }
  22837. // Animations
  22838. if (parsedCamera.animations) {
  22839. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22840. var parsedAnimation = parsedCamera.animations[animationIndex];
  22841. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22842. }
  22843. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22844. }
  22845. if (parsedCamera.autoAnimate) {
  22846. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22847. }
  22848. return camera;
  22849. };
  22850. // Statics
  22851. Camera._PERSPECTIVE_CAMERA = 0;
  22852. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22853. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22854. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22855. Camera._RIG_MODE_NONE = 0;
  22856. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22857. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22858. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22859. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22860. Camera._RIG_MODE_VR = 20;
  22861. Camera._RIG_MODE_WEBVR = 21;
  22862. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22863. Camera.UseAlternateWebVRRendering = false;
  22864. __decorate([
  22865. BABYLON.serializeAsVector3()
  22866. ], Camera.prototype, "position", void 0);
  22867. __decorate([
  22868. BABYLON.serializeAsVector3()
  22869. ], Camera.prototype, "upVector", void 0);
  22870. __decorate([
  22871. BABYLON.serialize()
  22872. ], Camera.prototype, "orthoLeft", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Camera.prototype, "orthoRight", void 0);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Camera.prototype, "orthoBottom", void 0);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Camera.prototype, "orthoTop", void 0);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Camera.prototype, "fov", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "minZ", void 0);
  22888. __decorate([
  22889. BABYLON.serialize()
  22890. ], Camera.prototype, "maxZ", void 0);
  22891. __decorate([
  22892. BABYLON.serialize()
  22893. ], Camera.prototype, "inertia", void 0);
  22894. __decorate([
  22895. BABYLON.serialize()
  22896. ], Camera.prototype, "mode", void 0);
  22897. __decorate([
  22898. BABYLON.serialize()
  22899. ], Camera.prototype, "layerMask", void 0);
  22900. __decorate([
  22901. BABYLON.serialize()
  22902. ], Camera.prototype, "fovMode", void 0);
  22903. __decorate([
  22904. BABYLON.serialize()
  22905. ], Camera.prototype, "cameraRigMode", void 0);
  22906. __decorate([
  22907. BABYLON.serialize()
  22908. ], Camera.prototype, "interaxialDistance", void 0);
  22909. __decorate([
  22910. BABYLON.serialize()
  22911. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22912. return Camera;
  22913. }(BABYLON.Node));
  22914. BABYLON.Camera = Camera;
  22915. })(BABYLON || (BABYLON = {}));
  22916. //# sourceMappingURL=babylon.camera.js.map
  22917. var BABYLON;
  22918. (function (BABYLON) {
  22919. var RenderingManager = /** @class */ (function () {
  22920. function RenderingManager(scene) {
  22921. this._renderingGroups = new Array();
  22922. this._autoClearDepthStencil = {};
  22923. this._customOpaqueSortCompareFn = {};
  22924. this._customAlphaTestSortCompareFn = {};
  22925. this._customTransparentSortCompareFn = {};
  22926. this._renderinGroupInfo = null;
  22927. this._scene = scene;
  22928. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22929. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22930. }
  22931. }
  22932. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22933. if (depth === void 0) { depth = true; }
  22934. if (stencil === void 0) { stencil = true; }
  22935. if (this._depthStencilBufferAlreadyCleaned) {
  22936. return;
  22937. }
  22938. this._scene.getEngine().clear(null, false, depth, stencil);
  22939. this._depthStencilBufferAlreadyCleaned = true;
  22940. };
  22941. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22942. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22943. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22944. var info = null;
  22945. if (observable) {
  22946. if (!this._renderinGroupInfo) {
  22947. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22948. }
  22949. info = this._renderinGroupInfo;
  22950. info.scene = this._scene;
  22951. info.camera = this._scene.activeCamera;
  22952. }
  22953. // Dispatch sprites
  22954. if (renderSprites) {
  22955. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22956. var manager = this._scene.spriteManagers[index];
  22957. this.dispatchSprites(manager);
  22958. }
  22959. }
  22960. // Render
  22961. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22962. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22963. var renderingGroup = this._renderingGroups[index];
  22964. if (!renderingGroup && !observable)
  22965. continue;
  22966. var renderingGroupMask = 0;
  22967. // Fire PRECLEAR stage
  22968. if (observable && info) {
  22969. renderingGroupMask = Math.pow(2, index);
  22970. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22971. info.renderingGroupId = index;
  22972. observable.notifyObservers(info, renderingGroupMask);
  22973. }
  22974. // Clear depth/stencil if needed
  22975. if (RenderingManager.AUTOCLEAR) {
  22976. var autoClear = this._autoClearDepthStencil[index];
  22977. if (autoClear && autoClear.autoClear) {
  22978. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22979. }
  22980. }
  22981. if (observable && info) {
  22982. // Fire PREOPAQUE stage
  22983. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22984. observable.notifyObservers(info, renderingGroupMask);
  22985. // Fire PRETRANSPARENT stage
  22986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22987. observable.notifyObservers(info, renderingGroupMask);
  22988. }
  22989. if (renderingGroup)
  22990. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22991. // Fire POSTTRANSPARENT stage
  22992. if (observable && info) {
  22993. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22994. observable.notifyObservers(info, renderingGroupMask);
  22995. }
  22996. }
  22997. };
  22998. RenderingManager.prototype.reset = function () {
  22999. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23000. var renderingGroup = this._renderingGroups[index];
  23001. if (renderingGroup) {
  23002. renderingGroup.prepare();
  23003. }
  23004. }
  23005. };
  23006. RenderingManager.prototype.dispose = function () {
  23007. this.freeRenderingGroups();
  23008. this._renderingGroups.length = 0;
  23009. };
  23010. /**
  23011. * Clear the info related to rendering groups preventing retention points during dispose.
  23012. */
  23013. RenderingManager.prototype.freeRenderingGroups = function () {
  23014. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23015. var renderingGroup = this._renderingGroups[index];
  23016. if (renderingGroup) {
  23017. renderingGroup.dispose();
  23018. }
  23019. }
  23020. };
  23021. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23022. if (this._renderingGroups[renderingGroupId] === undefined) {
  23023. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23024. }
  23025. };
  23026. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23027. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23028. this._prepareRenderingGroup(renderingGroupId);
  23029. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23030. };
  23031. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23032. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23033. this._prepareRenderingGroup(renderingGroupId);
  23034. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23035. };
  23036. /**
  23037. * @param subMesh The submesh to dispatch
  23038. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23039. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23040. */
  23041. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23042. if (mesh === undefined) {
  23043. mesh = subMesh.getMesh();
  23044. }
  23045. var renderingGroupId = mesh.renderingGroupId || 0;
  23046. this._prepareRenderingGroup(renderingGroupId);
  23047. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23048. };
  23049. /**
  23050. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23051. * This allowed control for front to back rendering or reversly depending of the special needs.
  23052. *
  23053. * @param renderingGroupId The rendering group id corresponding to its index
  23054. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23055. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23056. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23057. */
  23058. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23059. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23060. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23061. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23062. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23063. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23064. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23065. if (this._renderingGroups[renderingGroupId]) {
  23066. var group = this._renderingGroups[renderingGroupId];
  23067. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23068. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23069. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23070. }
  23071. };
  23072. /**
  23073. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23074. *
  23075. * @param renderingGroupId The rendering group id corresponding to its index
  23076. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23077. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23078. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23079. */
  23080. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23081. if (depth === void 0) { depth = true; }
  23082. if (stencil === void 0) { stencil = true; }
  23083. this._autoClearDepthStencil[renderingGroupId] = {
  23084. autoClear: autoClearDepthStencil,
  23085. depth: depth,
  23086. stencil: stencil
  23087. };
  23088. };
  23089. /**
  23090. * The max id used for rendering groups (not included)
  23091. */
  23092. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23093. /**
  23094. * The min id used for rendering groups (included)
  23095. */
  23096. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23097. /**
  23098. * Used to globally prevent autoclearing scenes.
  23099. */
  23100. RenderingManager.AUTOCLEAR = true;
  23101. return RenderingManager;
  23102. }());
  23103. BABYLON.RenderingManager = RenderingManager;
  23104. })(BABYLON || (BABYLON = {}));
  23105. //# sourceMappingURL=babylon.renderingManager.js.map
  23106. var BABYLON;
  23107. (function (BABYLON) {
  23108. var RenderingGroup = /** @class */ (function () {
  23109. /**
  23110. * Creates a new rendering group.
  23111. * @param index The rendering group index
  23112. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23113. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23114. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23115. */
  23116. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23117. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23118. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23119. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23120. this.index = index;
  23121. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23122. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23123. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23124. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23125. this._particleSystems = new BABYLON.SmartArray(256);
  23126. this._spriteManagers = new BABYLON.SmartArray(256);
  23127. this._edgesRenderers = new BABYLON.SmartArray(16);
  23128. this._scene = scene;
  23129. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23130. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23131. this.transparentSortCompareFn = transparentSortCompareFn;
  23132. }
  23133. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23134. /**
  23135. * Set the opaque sort comparison function.
  23136. * If null the sub meshes will be render in the order they were created
  23137. */
  23138. set: function (value) {
  23139. this._opaqueSortCompareFn = value;
  23140. if (value) {
  23141. this._renderOpaque = this.renderOpaqueSorted;
  23142. }
  23143. else {
  23144. this._renderOpaque = RenderingGroup.renderUnsorted;
  23145. }
  23146. },
  23147. enumerable: true,
  23148. configurable: true
  23149. });
  23150. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23151. /**
  23152. * Set the alpha test sort comparison function.
  23153. * If null the sub meshes will be render in the order they were created
  23154. */
  23155. set: function (value) {
  23156. this._alphaTestSortCompareFn = value;
  23157. if (value) {
  23158. this._renderAlphaTest = this.renderAlphaTestSorted;
  23159. }
  23160. else {
  23161. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23162. }
  23163. },
  23164. enumerable: true,
  23165. configurable: true
  23166. });
  23167. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23168. /**
  23169. * Set the transparent sort comparison function.
  23170. * If null the sub meshes will be render in the order they were created
  23171. */
  23172. set: function (value) {
  23173. if (value) {
  23174. this._transparentSortCompareFn = value;
  23175. }
  23176. else {
  23177. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23178. }
  23179. this._renderTransparent = this.renderTransparentSorted;
  23180. },
  23181. enumerable: true,
  23182. configurable: true
  23183. });
  23184. /**
  23185. * Render all the sub meshes contained in the group.
  23186. * @param customRenderFunction Used to override the default render behaviour of the group.
  23187. * @returns true if rendered some submeshes.
  23188. */
  23189. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23190. if (customRenderFunction) {
  23191. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23192. return;
  23193. }
  23194. var engine = this._scene.getEngine();
  23195. // Depth only
  23196. if (this._depthOnlySubMeshes.length !== 0) {
  23197. engine.setColorWrite(false);
  23198. this._renderAlphaTest(this._depthOnlySubMeshes);
  23199. engine.setColorWrite(true);
  23200. }
  23201. // Opaque
  23202. if (this._opaqueSubMeshes.length !== 0) {
  23203. this._renderOpaque(this._opaqueSubMeshes);
  23204. }
  23205. // Alpha test
  23206. if (this._alphaTestSubMeshes.length !== 0) {
  23207. this._renderAlphaTest(this._alphaTestSubMeshes);
  23208. }
  23209. var stencilState = engine.getStencilBuffer();
  23210. engine.setStencilBuffer(false);
  23211. // Sprites
  23212. if (renderSprites) {
  23213. this._renderSprites();
  23214. }
  23215. // Particles
  23216. if (renderParticles) {
  23217. this._renderParticles(activeMeshes);
  23218. }
  23219. if (this.onBeforeTransparentRendering) {
  23220. this.onBeforeTransparentRendering();
  23221. }
  23222. // Transparent
  23223. if (this._transparentSubMeshes.length !== 0) {
  23224. this._renderTransparent(this._transparentSubMeshes);
  23225. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23226. }
  23227. // Set back stencil to false in case it changes before the edge renderer.
  23228. engine.setStencilBuffer(false);
  23229. // Edges
  23230. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23231. this._edgesRenderers.data[edgesRendererIndex].render();
  23232. }
  23233. // Restore Stencil state.
  23234. engine.setStencilBuffer(stencilState);
  23235. };
  23236. /**
  23237. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23238. * @param subMeshes The submeshes to render
  23239. */
  23240. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23241. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23242. };
  23243. /**
  23244. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23245. * @param subMeshes The submeshes to render
  23246. */
  23247. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23248. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23249. };
  23250. /**
  23251. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23252. * @param subMeshes The submeshes to render
  23253. */
  23254. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23255. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23256. };
  23257. /**
  23258. * Renders the submeshes in a specified order.
  23259. * @param subMeshes The submeshes to sort before render
  23260. * @param sortCompareFn The comparison function use to sort
  23261. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23262. * @param transparent Specifies to activate blending if true
  23263. */
  23264. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23265. var subIndex = 0;
  23266. var subMesh;
  23267. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23268. for (; subIndex < subMeshes.length; subIndex++) {
  23269. subMesh = subMeshes.data[subIndex];
  23270. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23271. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23272. }
  23273. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23274. if (sortCompareFn) {
  23275. sortedArray.sort(sortCompareFn);
  23276. }
  23277. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23278. subMesh = sortedArray[subIndex];
  23279. if (transparent) {
  23280. var material = subMesh.getMaterial();
  23281. if (material && material.needDepthPrePass) {
  23282. var engine = material.getScene().getEngine();
  23283. engine.setColorWrite(false);
  23284. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23285. subMesh.render(false);
  23286. engine.setColorWrite(true);
  23287. }
  23288. }
  23289. subMesh.render(transparent);
  23290. }
  23291. };
  23292. /**
  23293. * Renders the submeshes in the order they were dispatched (no sort applied).
  23294. * @param subMeshes The submeshes to render
  23295. */
  23296. RenderingGroup.renderUnsorted = function (subMeshes) {
  23297. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23298. var submesh = subMeshes.data[subIndex];
  23299. submesh.render(false);
  23300. }
  23301. };
  23302. /**
  23303. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23304. * are rendered back to front if in the same alpha index.
  23305. *
  23306. * @param a The first submesh
  23307. * @param b The second submesh
  23308. * @returns The result of the comparison
  23309. */
  23310. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23311. // Alpha index first
  23312. if (a._alphaIndex > b._alphaIndex) {
  23313. return 1;
  23314. }
  23315. if (a._alphaIndex < b._alphaIndex) {
  23316. return -1;
  23317. }
  23318. // Then distance to camera
  23319. return RenderingGroup.backToFrontSortCompare(a, b);
  23320. };
  23321. /**
  23322. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23323. * are rendered back to front.
  23324. *
  23325. * @param a The first submesh
  23326. * @param b The second submesh
  23327. * @returns The result of the comparison
  23328. */
  23329. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23330. // Then distance to camera
  23331. if (a._distanceToCamera < b._distanceToCamera) {
  23332. return 1;
  23333. }
  23334. if (a._distanceToCamera > b._distanceToCamera) {
  23335. return -1;
  23336. }
  23337. return 0;
  23338. };
  23339. /**
  23340. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23341. * are rendered front to back (prevent overdraw).
  23342. *
  23343. * @param a The first submesh
  23344. * @param b The second submesh
  23345. * @returns The result of the comparison
  23346. */
  23347. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23348. // Then distance to camera
  23349. if (a._distanceToCamera < b._distanceToCamera) {
  23350. return -1;
  23351. }
  23352. if (a._distanceToCamera > b._distanceToCamera) {
  23353. return 1;
  23354. }
  23355. return 0;
  23356. };
  23357. /**
  23358. * Resets the different lists of submeshes to prepare a new frame.
  23359. */
  23360. RenderingGroup.prototype.prepare = function () {
  23361. this._opaqueSubMeshes.reset();
  23362. this._transparentSubMeshes.reset();
  23363. this._alphaTestSubMeshes.reset();
  23364. this._depthOnlySubMeshes.reset();
  23365. this._particleSystems.reset();
  23366. this._spriteManagers.reset();
  23367. this._edgesRenderers.reset();
  23368. };
  23369. RenderingGroup.prototype.dispose = function () {
  23370. this._opaqueSubMeshes.dispose();
  23371. this._transparentSubMeshes.dispose();
  23372. this._alphaTestSubMeshes.dispose();
  23373. this._depthOnlySubMeshes.dispose();
  23374. this._particleSystems.dispose();
  23375. this._spriteManagers.dispose();
  23376. this._edgesRenderers.dispose();
  23377. };
  23378. /**
  23379. * Inserts the submesh in its correct queue depending on its material.
  23380. * @param subMesh The submesh to dispatch
  23381. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23382. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23383. */
  23384. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23385. // Get mesh and materials if not provided
  23386. if (mesh === undefined) {
  23387. mesh = subMesh.getMesh();
  23388. }
  23389. if (material === undefined) {
  23390. material = subMesh.getMaterial();
  23391. }
  23392. if (material === null || material === undefined) {
  23393. return;
  23394. }
  23395. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23396. this._transparentSubMeshes.push(subMesh);
  23397. }
  23398. else if (material.needAlphaTesting()) { // Alpha test
  23399. if (material.needDepthPrePass) {
  23400. this._depthOnlySubMeshes.push(subMesh);
  23401. }
  23402. this._alphaTestSubMeshes.push(subMesh);
  23403. }
  23404. else {
  23405. if (material.needDepthPrePass) {
  23406. this._depthOnlySubMeshes.push(subMesh);
  23407. }
  23408. this._opaqueSubMeshes.push(subMesh); // Opaque
  23409. }
  23410. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23411. this._edgesRenderers.push(mesh._edgesRenderer);
  23412. }
  23413. };
  23414. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23415. this._spriteManagers.push(spriteManager);
  23416. };
  23417. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23418. this._particleSystems.push(particleSystem);
  23419. };
  23420. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23421. if (this._particleSystems.length === 0) {
  23422. return;
  23423. }
  23424. // Particles
  23425. var activeCamera = this._scene.activeCamera;
  23426. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23427. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23428. var particleSystem = this._particleSystems.data[particleIndex];
  23429. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23430. continue;
  23431. }
  23432. var emitter = particleSystem.emitter;
  23433. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23434. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23435. }
  23436. }
  23437. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23438. };
  23439. RenderingGroup.prototype._renderSprites = function () {
  23440. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23441. return;
  23442. }
  23443. // Sprites
  23444. var activeCamera = this._scene.activeCamera;
  23445. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23446. for (var id = 0; id < this._spriteManagers.length; id++) {
  23447. var spriteManager = this._spriteManagers.data[id];
  23448. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23449. spriteManager.render();
  23450. }
  23451. }
  23452. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23453. };
  23454. return RenderingGroup;
  23455. }());
  23456. BABYLON.RenderingGroup = RenderingGroup;
  23457. })(BABYLON || (BABYLON = {}));
  23458. //# sourceMappingURL=babylon.renderingGroup.js.map
  23459. var BABYLON;
  23460. (function (BABYLON) {
  23461. /** @hidden */
  23462. var ClickInfo = /** @class */ (function () {
  23463. function ClickInfo() {
  23464. this._singleClick = false;
  23465. this._doubleClick = false;
  23466. this._hasSwiped = false;
  23467. this._ignore = false;
  23468. }
  23469. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23470. get: function () {
  23471. return this._singleClick;
  23472. },
  23473. set: function (b) {
  23474. this._singleClick = b;
  23475. },
  23476. enumerable: true,
  23477. configurable: true
  23478. });
  23479. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23480. get: function () {
  23481. return this._doubleClick;
  23482. },
  23483. set: function (b) {
  23484. this._doubleClick = b;
  23485. },
  23486. enumerable: true,
  23487. configurable: true
  23488. });
  23489. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23490. get: function () {
  23491. return this._hasSwiped;
  23492. },
  23493. set: function (b) {
  23494. this._hasSwiped = b;
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23500. get: function () {
  23501. return this._ignore;
  23502. },
  23503. set: function (b) {
  23504. this._ignore = b;
  23505. },
  23506. enumerable: true,
  23507. configurable: true
  23508. });
  23509. return ClickInfo;
  23510. }());
  23511. /**
  23512. * This class is used by the onRenderingGroupObservable
  23513. */
  23514. var RenderingGroupInfo = /** @class */ (function () {
  23515. function RenderingGroupInfo() {
  23516. }
  23517. /**
  23518. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23519. * This stage will be fired no matter what
  23520. */
  23521. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23522. /**
  23523. * Called before opaque object are rendered.
  23524. * This stage will be fired only if there's 3D Opaque content to render
  23525. */
  23526. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23527. /**
  23528. * Called after the opaque objects are rendered and before the transparent ones
  23529. * This stage will be fired only if there's 3D transparent content to render
  23530. */
  23531. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23532. /**
  23533. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23534. * This stage will be fired no matter what
  23535. */
  23536. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23537. return RenderingGroupInfo;
  23538. }());
  23539. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23540. /**
  23541. * Represents a scene to be rendered by the engine.
  23542. * @see http://doc.babylonjs.com/features/scene
  23543. */
  23544. var Scene = /** @class */ (function () {
  23545. /**
  23546. * Creates a new Scene
  23547. * @param engine defines the engine to use to render this scene
  23548. */
  23549. function Scene(engine) {
  23550. // Members
  23551. /**
  23552. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23553. */
  23554. this.autoClear = true;
  23555. /**
  23556. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23557. */
  23558. this.autoClearDepthAndStencil = true;
  23559. /**
  23560. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23561. */
  23562. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23563. /**
  23564. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23565. */
  23566. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23567. this._forceWireframe = false;
  23568. this._forcePointsCloud = false;
  23569. /**
  23570. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23571. */
  23572. this.forceShowBoundingBoxes = false;
  23573. /**
  23574. * Gets or sets a boolean indicating if animations are enabled
  23575. */
  23576. this.animationsEnabled = true;
  23577. this._animationPropertiesOverride = null;
  23578. /**
  23579. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23580. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23581. */
  23582. this.useConstantAnimationDeltaTime = false;
  23583. /**
  23584. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23585. * Please note that it requires to run a ray cast through the scene on every frame
  23586. */
  23587. this.constantlyUpdateMeshUnderPointer = false;
  23588. /**
  23589. * Defines the HTML cursor to use when hovering over interactive elements
  23590. */
  23591. this.hoverCursor = "pointer";
  23592. /**
  23593. * Defines the HTML default cursor to use (empty by default)
  23594. */
  23595. this.defaultCursor = "";
  23596. /**
  23597. * This is used to call preventDefault() on pointer down
  23598. * in order to block unwanted artifacts like system double clicks
  23599. */
  23600. this.preventDefaultOnPointerDown = true;
  23601. // Metadata
  23602. /**
  23603. * Gets or sets user defined metadata
  23604. */
  23605. this.metadata = null;
  23606. /**
  23607. * Use this array to add regular expressions used to disable offline support for specific urls
  23608. */
  23609. this.disableOfflineSupportExceptionRules = new Array();
  23610. /**
  23611. * An event triggered when the scene is disposed.
  23612. */
  23613. this.onDisposeObservable = new BABYLON.Observable();
  23614. this._onDisposeObserver = null;
  23615. /**
  23616. * An event triggered before rendering the scene (right after animations and physics)
  23617. */
  23618. this.onBeforeRenderObservable = new BABYLON.Observable();
  23619. this._onBeforeRenderObserver = null;
  23620. /**
  23621. * An event triggered after rendering the scene
  23622. */
  23623. this.onAfterRenderObservable = new BABYLON.Observable();
  23624. this._onAfterRenderObserver = null;
  23625. /**
  23626. * An event triggered before animating the scene
  23627. */
  23628. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered after animations processing
  23631. */
  23632. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23633. /**
  23634. * An event triggered before draw calls are ready to be sent
  23635. */
  23636. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23637. /**
  23638. * An event triggered after draw calls have been sent
  23639. */
  23640. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23641. /**
  23642. * An event triggered when physic simulation is about to be run
  23643. */
  23644. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23645. /**
  23646. * An event triggered when physic simulation has been done
  23647. */
  23648. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23649. /**
  23650. * An event triggered when the scene is ready
  23651. */
  23652. this.onReadyObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered before rendering a camera
  23655. */
  23656. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23657. this._onBeforeCameraRenderObserver = null;
  23658. /**
  23659. * An event triggered after rendering a camera
  23660. */
  23661. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23662. this._onAfterCameraRenderObserver = null;
  23663. /**
  23664. * An event triggered when active meshes evaluation is about to start
  23665. */
  23666. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23667. /**
  23668. * An event triggered when active meshes evaluation is done
  23669. */
  23670. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23671. /**
  23672. * An event triggered when particles rendering is about to start
  23673. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23674. */
  23675. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23676. /**
  23677. * An event triggered when particles rendering is done
  23678. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23679. */
  23680. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23681. /**
  23682. * An event triggered when sprites rendering is about to start
  23683. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23684. */
  23685. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered when sprites rendering is done
  23688. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23689. */
  23690. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23693. */
  23694. this.onDataLoadedObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered when a camera is created
  23697. */
  23698. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered when a camera is removed
  23701. */
  23702. this.onCameraRemovedObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered when a light is created
  23705. */
  23706. this.onNewLightAddedObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when a light is removed
  23709. */
  23710. this.onLightRemovedObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when a geometry is created
  23713. */
  23714. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23715. /**
  23716. * An event triggered when a geometry is removed
  23717. */
  23718. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23719. /**
  23720. * An event triggered when a transform node is created
  23721. */
  23722. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23723. /**
  23724. * An event triggered when a transform node is removed
  23725. */
  23726. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23727. /**
  23728. * An event triggered when a mesh is created
  23729. */
  23730. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23731. /**
  23732. * An event triggered when a mesh is removed
  23733. */
  23734. this.onMeshRemovedObservable = new BABYLON.Observable();
  23735. /**
  23736. * An event triggered when render targets are about to be rendered
  23737. * Can happen multiple times per frame.
  23738. */
  23739. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when render targets were rendered.
  23742. * Can happen multiple times per frame.
  23743. */
  23744. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23745. /**
  23746. * An event triggered before calculating deterministic simulation step
  23747. */
  23748. this.onBeforeStepObservable = new BABYLON.Observable();
  23749. /**
  23750. * An event triggered after calculating deterministic simulation step
  23751. */
  23752. this.onAfterStepObservable = new BABYLON.Observable();
  23753. /**
  23754. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23755. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23756. * 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)
  23757. */
  23758. this.onRenderingGroupObservable = new BABYLON.Observable();
  23759. // Animations
  23760. /**
  23761. * Gets a list of Animations associated with the scene
  23762. */
  23763. this.animations = [];
  23764. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23765. /**
  23766. * 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).
  23767. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23768. */
  23769. this.onPrePointerObservable = new BABYLON.Observable();
  23770. /**
  23771. * Observable event triggered each time an input event is received from the rendering canvas
  23772. */
  23773. this.onPointerObservable = new BABYLON.Observable();
  23774. this._meshPickProceed = false;
  23775. this._currentPickResult = null;
  23776. this._previousPickResult = null;
  23777. this._totalPointersPressed = 0;
  23778. this._doubleClickOccured = false;
  23779. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23780. this.cameraToUseForPointers = null;
  23781. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23782. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23783. this._startingPointerTime = 0;
  23784. this._previousStartingPointerTime = 0;
  23785. this._pointerCaptures = {};
  23786. // Deterministic lockstep
  23787. this._timeAccumulator = 0;
  23788. this._currentStepId = 0;
  23789. this._currentInternalStep = 0;
  23790. // Keyboard
  23791. /**
  23792. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23793. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23794. */
  23795. this.onPreKeyboardObservable = new BABYLON.Observable();
  23796. /**
  23797. * Observable event triggered each time an keyboard event is received from the hosting window
  23798. */
  23799. this.onKeyboardObservable = new BABYLON.Observable();
  23800. // Coordinates system
  23801. this._useRightHandedSystem = false;
  23802. // Fog
  23803. this._fogEnabled = true;
  23804. this._fogMode = Scene.FOGMODE_NONE;
  23805. /**
  23806. * Gets or sets the fog color to use
  23807. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23808. */
  23809. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23810. /**
  23811. * Gets or sets the fog density to use
  23812. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23813. */
  23814. this.fogDensity = 0.1;
  23815. /**
  23816. * Gets or sets the fog start distance to use
  23817. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23818. */
  23819. this.fogStart = 0;
  23820. /**
  23821. * Gets or sets the fog end distance to use
  23822. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23823. */
  23824. this.fogEnd = 1000.0;
  23825. // Lights
  23826. this._shadowsEnabled = true;
  23827. this._lightsEnabled = true;
  23828. /**
  23829. * All of the lights added to this scene
  23830. * @see http://doc.babylonjs.com/babylon101/lights
  23831. */
  23832. this.lights = new Array();
  23833. // Cameras
  23834. /** All of the cameras added to this scene.
  23835. * @see http://doc.babylonjs.com/babylon101/cameras
  23836. */
  23837. this.cameras = new Array();
  23838. /** All of the active cameras added to this scene. */
  23839. this.activeCameras = new Array();
  23840. // Meshes
  23841. /**
  23842. * All of the tranform nodes added to this scene
  23843. * @see http://doc.babylonjs.com/how_to/transformnode
  23844. */
  23845. this.transformNodes = new Array();
  23846. /**
  23847. * All of the (abstract) meshes added to this scene
  23848. */
  23849. this.meshes = new Array();
  23850. /**
  23851. * All of the animation groups added to this scene
  23852. * @see http://doc.babylonjs.com/how_to/group
  23853. */
  23854. this.animationGroups = new Array();
  23855. // Geometries
  23856. this._geometries = new Array();
  23857. /**
  23858. * All of the materials added to this scene
  23859. * @see http://doc.babylonjs.com/babylon101/materials
  23860. */
  23861. this.materials = new Array();
  23862. /**
  23863. * All of the multi-materials added to this scene
  23864. * @see http://doc.babylonjs.com/how_to/multi_materials
  23865. */
  23866. this.multiMaterials = new Array();
  23867. // Textures
  23868. this._texturesEnabled = true;
  23869. /**
  23870. * All of the textures added to this scene
  23871. */
  23872. this.textures = new Array();
  23873. // Particles
  23874. /**
  23875. * Gets or sets a boolean indicating if particles are enabled on this scene
  23876. */
  23877. this.particlesEnabled = true;
  23878. /**
  23879. * All of the particle systems added to this scene
  23880. * @see http://doc.babylonjs.com/babylon101/particles
  23881. */
  23882. this.particleSystems = new Array();
  23883. // Sprites
  23884. /**
  23885. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23886. */
  23887. this.spritesEnabled = true;
  23888. /**
  23889. * All of the sprite managers added to this scene
  23890. * @see http://doc.babylonjs.com/babylon101/sprites
  23891. */
  23892. this.spriteManagers = new Array();
  23893. /**
  23894. * The list of layers (background and foreground) of the scene
  23895. */
  23896. this.layers = new Array();
  23897. /**
  23898. * The list of effect layers (highlights/glow) added to the scene
  23899. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23900. * @see http://doc.babylonjs.com/how_to/glow_layer
  23901. */
  23902. this.effectLayers = new Array();
  23903. // Skeletons
  23904. this._skeletonsEnabled = true;
  23905. /**
  23906. * The list of skeletons added to the scene
  23907. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23908. */
  23909. this.skeletons = new Array();
  23910. // Morph targets
  23911. /**
  23912. * The list of morph target managers added to the scene
  23913. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23914. */
  23915. this.morphTargetManagers = new Array();
  23916. // Lens flares
  23917. /**
  23918. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23919. */
  23920. this.lensFlaresEnabled = true;
  23921. /**
  23922. * The list of lens flare system added to the scene
  23923. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23924. */
  23925. this.lensFlareSystems = new Array();
  23926. // Collisions
  23927. /**
  23928. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23929. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23930. */
  23931. this.collisionsEnabled = true;
  23932. /**
  23933. * Defines the gravity applied to this scene (used only for collisions)
  23934. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23935. */
  23936. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23937. // Postprocesses
  23938. /**
  23939. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23940. */
  23941. this.postProcessesEnabled = true;
  23942. /**
  23943. * The list of postprocesses added to the scene
  23944. */
  23945. this.postProcesses = new Array();
  23946. // Customs render targets
  23947. /**
  23948. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23949. */
  23950. this.renderTargetsEnabled = true;
  23951. /**
  23952. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23953. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23954. */
  23955. this.dumpNextRenderTargets = false;
  23956. /**
  23957. * The list of user defined render targets added to the scene
  23958. */
  23959. this.customRenderTargets = new Array();
  23960. /**
  23961. * Gets the list of meshes imported to the scene through SceneLoader
  23962. */
  23963. this.importedMeshesFiles = new Array();
  23964. // Probes
  23965. /**
  23966. * Gets or sets a boolean indicating if probes are enabled on this scene
  23967. */
  23968. this.probesEnabled = true;
  23969. /**
  23970. * The list of reflection probes added to the scene
  23971. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23972. */
  23973. this.reflectionProbes = new Array();
  23974. /** @hidden */
  23975. this._actionManagers = new Array();
  23976. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23977. // Procedural textures
  23978. /**
  23979. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23980. */
  23981. this.proceduralTexturesEnabled = true;
  23982. /**
  23983. * The list of procedural textures added to the scene
  23984. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23985. */
  23986. this.proceduralTextures = new Array();
  23987. /**
  23988. * The list of sound tracks added to the scene
  23989. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23990. */
  23991. this.soundTracks = new Array();
  23992. this._audioEnabled = true;
  23993. this._headphone = false;
  23994. // Performance counters
  23995. this._totalVertices = new BABYLON.PerfCounter();
  23996. /** @hidden */
  23997. this._activeIndices = new BABYLON.PerfCounter();
  23998. /** @hidden */
  23999. this._activeParticles = new BABYLON.PerfCounter();
  24000. /** @hidden */
  24001. this._activeBones = new BABYLON.PerfCounter();
  24002. this._animationTime = 0;
  24003. /**
  24004. * Gets or sets a general scale for animation speed
  24005. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24006. */
  24007. this.animationTimeScale = 1;
  24008. this._renderId = 0;
  24009. this._executeWhenReadyTimeoutId = -1;
  24010. this._intermediateRendering = false;
  24011. this._viewUpdateFlag = -1;
  24012. this._projectionUpdateFlag = -1;
  24013. this._alternateViewUpdateFlag = -1;
  24014. this._alternateProjectionUpdateFlag = -1;
  24015. /** @hidden */
  24016. this._toBeDisposed = new BABYLON.SmartArray(256);
  24017. this._activeRequests = new Array();
  24018. this._pendingData = new Array();
  24019. this._isDisposed = false;
  24020. /**
  24021. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24022. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24023. */
  24024. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24025. this._activeMeshes = new BABYLON.SmartArray(256);
  24026. this._processedMaterials = new BABYLON.SmartArray(256);
  24027. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24028. /** @hidden */
  24029. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24030. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24031. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24032. /** @hidden */
  24033. this._activeAnimatables = new Array();
  24034. this._transformMatrix = BABYLON.Matrix.Zero();
  24035. this._useAlternateCameraConfiguration = false;
  24036. this._alternateRendering = false;
  24037. /**
  24038. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24039. * This is useful if there are more lights that the maximum simulteanous authorized
  24040. */
  24041. this.requireLightSorting = false;
  24042. this._depthRenderer = {};
  24043. this._activeMeshesFrozen = false;
  24044. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24045. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24046. this._engine.scenes.push(this);
  24047. this._uid = null;
  24048. this._renderingManager = new BABYLON.RenderingManager(this);
  24049. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24050. if (BABYLON.OutlineRenderer) {
  24051. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24052. }
  24053. if (BABYLON.Tools.IsWindowObjectExist()) {
  24054. this.attachControl();
  24055. }
  24056. //simplification queue
  24057. if (BABYLON.SimplificationQueue) {
  24058. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24059. }
  24060. //collision coordinator initialization. For now legacy per default.
  24061. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24062. // Uniform Buffer
  24063. this._createUbo();
  24064. // Default Image processing definition.
  24065. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24066. }
  24067. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24068. /** The fog is deactivated */
  24069. get: function () {
  24070. return Scene._FOGMODE_NONE;
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24076. /** The fog density is following an exponential function */
  24077. get: function () {
  24078. return Scene._FOGMODE_EXP;
  24079. },
  24080. enumerable: true,
  24081. configurable: true
  24082. });
  24083. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24084. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24085. get: function () {
  24086. return Scene._FOGMODE_EXP2;
  24087. },
  24088. enumerable: true,
  24089. configurable: true
  24090. });
  24091. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24092. /** The fog density is following a linear function. */
  24093. get: function () {
  24094. return Scene._FOGMODE_LINEAR;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24100. /**
  24101. * Texture used in all pbr material as the reflection texture.
  24102. * As in the majority of the scene they are the same (exception for multi room and so on),
  24103. * this is easier to reference from here than from all the materials.
  24104. */
  24105. get: function () {
  24106. return this._environmentTexture;
  24107. },
  24108. /**
  24109. * Texture used in all pbr material as the reflection texture.
  24110. * As in the majority of the scene they are the same (exception for multi room and so on),
  24111. * this is easier to set here than in all the materials.
  24112. */
  24113. set: function (value) {
  24114. if (this._environmentTexture === value) {
  24115. return;
  24116. }
  24117. this._environmentTexture = value;
  24118. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24119. },
  24120. enumerable: true,
  24121. configurable: true
  24122. });
  24123. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24124. /**
  24125. * Default image processing configuration used either in the rendering
  24126. * Forward main pass or through the imageProcessingPostProcess if present.
  24127. * As in the majority of the scene they are the same (exception for multi camera),
  24128. * this is easier to reference from here than from all the materials and post process.
  24129. *
  24130. * No setter as we it is a shared configuration, you can set the values instead.
  24131. */
  24132. get: function () {
  24133. return this._imageProcessingConfiguration;
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24139. get: function () {
  24140. return this._forceWireframe;
  24141. },
  24142. /**
  24143. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24144. */
  24145. set: function (value) {
  24146. if (this._forceWireframe === value) {
  24147. return;
  24148. }
  24149. this._forceWireframe = value;
  24150. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24156. get: function () {
  24157. return this._forcePointsCloud;
  24158. },
  24159. /**
  24160. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24161. */
  24162. set: function (value) {
  24163. if (this._forcePointsCloud === value) {
  24164. return;
  24165. }
  24166. this._forcePointsCloud = value;
  24167. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24173. /**
  24174. * Gets or sets the animation properties override
  24175. */
  24176. get: function () {
  24177. return this._animationPropertiesOverride;
  24178. },
  24179. set: function (value) {
  24180. this._animationPropertiesOverride = value;
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene.prototype, "onDispose", {
  24186. /** Sets a function to be executed when this scene is disposed. */
  24187. set: function (callback) {
  24188. if (this._onDisposeObserver) {
  24189. this.onDisposeObservable.remove(this._onDisposeObserver);
  24190. }
  24191. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24192. },
  24193. enumerable: true,
  24194. configurable: true
  24195. });
  24196. Object.defineProperty(Scene.prototype, "beforeRender", {
  24197. /** Sets a function to be executed before rendering this scene */
  24198. set: function (callback) {
  24199. if (this._onBeforeRenderObserver) {
  24200. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24201. }
  24202. if (callback) {
  24203. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24204. }
  24205. },
  24206. enumerable: true,
  24207. configurable: true
  24208. });
  24209. Object.defineProperty(Scene.prototype, "afterRender", {
  24210. /** Sets a function to be executed after rendering this scene */
  24211. set: function (callback) {
  24212. if (this._onAfterRenderObserver) {
  24213. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24214. }
  24215. if (callback) {
  24216. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24217. }
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24223. /** Sets a function to be executed before rendering a camera*/
  24224. set: function (callback) {
  24225. if (this._onBeforeCameraRenderObserver) {
  24226. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24227. }
  24228. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24229. },
  24230. enumerable: true,
  24231. configurable: true
  24232. });
  24233. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24234. /** Sets a function to be executed after rendering a camera*/
  24235. set: function (callback) {
  24236. if (this._onAfterCameraRenderObserver) {
  24237. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24238. }
  24239. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24245. /**
  24246. * Gets the gamepad manager associated with the scene
  24247. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24248. */
  24249. get: function () {
  24250. if (!this._gamepadManager) {
  24251. this._gamepadManager = new BABYLON.GamepadManager(this);
  24252. }
  24253. return this._gamepadManager;
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24259. /**
  24260. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24261. */
  24262. get: function () {
  24263. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24264. },
  24265. enumerable: true,
  24266. configurable: true
  24267. });
  24268. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24269. get: function () {
  24270. return this._useRightHandedSystem;
  24271. },
  24272. /**
  24273. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24274. */
  24275. set: function (value) {
  24276. if (this._useRightHandedSystem === value) {
  24277. return;
  24278. }
  24279. this._useRightHandedSystem = value;
  24280. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. /**
  24286. * Sets the step Id used by deterministic lock step
  24287. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24288. * @param newStepId defines the step Id
  24289. */
  24290. Scene.prototype.setStepId = function (newStepId) {
  24291. this._currentStepId = newStepId;
  24292. };
  24293. ;
  24294. /**
  24295. * Gets the step Id used by deterministic lock step
  24296. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24297. * @returns the step Id
  24298. */
  24299. Scene.prototype.getStepId = function () {
  24300. return this._currentStepId;
  24301. };
  24302. ;
  24303. /**
  24304. * Gets the internal step used by deterministic lock step
  24305. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24306. * @returns the internal step
  24307. */
  24308. Scene.prototype.getInternalStep = function () {
  24309. return this._currentInternalStep;
  24310. };
  24311. ;
  24312. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24313. get: function () {
  24314. return this._fogEnabled;
  24315. },
  24316. /**
  24317. * Gets or sets a boolean indicating if fog is enabled on this scene
  24318. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24319. */
  24320. set: function (value) {
  24321. if (this._fogEnabled === value) {
  24322. return;
  24323. }
  24324. this._fogEnabled = value;
  24325. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Scene.prototype, "fogMode", {
  24331. get: function () {
  24332. return this._fogMode;
  24333. },
  24334. /**
  24335. * Gets or sets the fog mode to use
  24336. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24337. */
  24338. set: function (value) {
  24339. if (this._fogMode === value) {
  24340. return;
  24341. }
  24342. this._fogMode = value;
  24343. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24344. },
  24345. enumerable: true,
  24346. configurable: true
  24347. });
  24348. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24349. get: function () {
  24350. return this._shadowsEnabled;
  24351. },
  24352. /**
  24353. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24354. */
  24355. set: function (value) {
  24356. if (this._shadowsEnabled === value) {
  24357. return;
  24358. }
  24359. this._shadowsEnabled = value;
  24360. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24361. },
  24362. enumerable: true,
  24363. configurable: true
  24364. });
  24365. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24366. get: function () {
  24367. return this._lightsEnabled;
  24368. },
  24369. /**
  24370. * Gets or sets a boolean indicating if lights are enabled on this scene
  24371. */
  24372. set: function (value) {
  24373. if (this._lightsEnabled === value) {
  24374. return;
  24375. }
  24376. this._lightsEnabled = value;
  24377. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24383. /** The default material used on meshes when no material is affected */
  24384. get: function () {
  24385. if (!this._defaultMaterial) {
  24386. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24387. }
  24388. return this._defaultMaterial;
  24389. },
  24390. /** The default material used on meshes when no material is affected */
  24391. set: function (value) {
  24392. this._defaultMaterial = value;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24398. get: function () {
  24399. return this._texturesEnabled;
  24400. },
  24401. /**
  24402. * Gets or sets a boolean indicating if textures are enabled on this scene
  24403. */
  24404. set: function (value) {
  24405. if (this._texturesEnabled === value) {
  24406. return;
  24407. }
  24408. this._texturesEnabled = value;
  24409. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24415. get: function () {
  24416. return this._skeletonsEnabled;
  24417. },
  24418. /**
  24419. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24420. */
  24421. set: function (value) {
  24422. if (this._skeletonsEnabled === value) {
  24423. return;
  24424. }
  24425. this._skeletonsEnabled = value;
  24426. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24432. /**
  24433. * Gets the postprocess render pipeline manager
  24434. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24435. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24436. */
  24437. get: function () {
  24438. if (!this._postProcessRenderPipelineManager) {
  24439. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24440. }
  24441. return this._postProcessRenderPipelineManager;
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24447. /**
  24448. * Gets the main soundtrack associated with the scene
  24449. */
  24450. get: function () {
  24451. if (!this._mainSoundTrack) {
  24452. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24453. }
  24454. return this._mainSoundTrack;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24460. /** @hidden */
  24461. get: function () {
  24462. return this._alternateRendering;
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24468. /**
  24469. * Gets the list of frustum planes (built from the active camera)
  24470. */
  24471. get: function () {
  24472. return this._frustumPlanes;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24478. /**
  24479. * Gets the current geometry buffer associated to the scene.
  24480. */
  24481. get: function () {
  24482. return this._geometryBufferRenderer;
  24483. },
  24484. /**
  24485. * Sets the current geometry buffer for the scene.
  24486. */
  24487. set: function (geometryBufferRenderer) {
  24488. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24489. this._geometryBufferRenderer = geometryBufferRenderer;
  24490. }
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "debugLayer", {
  24496. /**
  24497. * Gets the debug layer associated with the scene
  24498. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24499. */
  24500. get: function () {
  24501. if (!this._debugLayer) {
  24502. this._debugLayer = new BABYLON.DebugLayer(this);
  24503. }
  24504. return this._debugLayer;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24510. /**
  24511. * Gets a boolean indicating if collisions are processed on a web worker
  24512. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24513. */
  24514. get: function () {
  24515. return this._workerCollisions;
  24516. },
  24517. set: function (enabled) {
  24518. if (!BABYLON.CollisionCoordinatorLegacy) {
  24519. return;
  24520. }
  24521. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24522. this._workerCollisions = enabled;
  24523. if (this.collisionCoordinator) {
  24524. this.collisionCoordinator.destroy();
  24525. }
  24526. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24527. this.collisionCoordinator.init(this);
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24533. /**
  24534. * Gets the octree used to boost mesh selection (picking)
  24535. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24536. */
  24537. get: function () {
  24538. return this._selectionOctree;
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24544. /**
  24545. * Gets the mesh that is currently under the pointer
  24546. */
  24547. get: function () {
  24548. return this._pointerOverMesh;
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "pointerX", {
  24554. /**
  24555. * Gets the current on-screen X position of the pointer
  24556. */
  24557. get: function () {
  24558. return this._pointerX;
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. Object.defineProperty(Scene.prototype, "pointerY", {
  24564. /**
  24565. * Gets the current on-screen Y position of the pointer
  24566. */
  24567. get: function () {
  24568. return this._pointerY;
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. /**
  24574. * Gets the cached material (ie. the latest rendered one)
  24575. * @returns the cached material
  24576. */
  24577. Scene.prototype.getCachedMaterial = function () {
  24578. return this._cachedMaterial;
  24579. };
  24580. /**
  24581. * Gets the cached effect (ie. the latest rendered one)
  24582. * @returns the cached effect
  24583. */
  24584. Scene.prototype.getCachedEffect = function () {
  24585. return this._cachedEffect;
  24586. };
  24587. /**
  24588. * Gets the cached visibility state (ie. the latest rendered one)
  24589. * @returns the cached visibility state
  24590. */
  24591. Scene.prototype.getCachedVisibility = function () {
  24592. return this._cachedVisibility;
  24593. };
  24594. /**
  24595. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24596. * @param material defines the current material
  24597. * @param effect defines the current effect
  24598. * @param visibility defines the current visibility state
  24599. * @returns true if one parameter is not cached
  24600. */
  24601. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24602. if (visibility === void 0) { visibility = 1; }
  24603. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24604. };
  24605. /**
  24606. * Gets the bounding box renderer associated with the scene
  24607. * @returns a BoundingBoxRenderer
  24608. */
  24609. Scene.prototype.getBoundingBoxRenderer = function () {
  24610. if (!this._boundingBoxRenderer) {
  24611. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24612. }
  24613. return this._boundingBoxRenderer;
  24614. };
  24615. /**
  24616. * Gets the outline renderer associated with the scene
  24617. * @returns a OutlineRenderer
  24618. */
  24619. Scene.prototype.getOutlineRenderer = function () {
  24620. return this._outlineRenderer;
  24621. };
  24622. /**
  24623. * Gets the engine associated with the scene
  24624. * @returns an Engine
  24625. */
  24626. Scene.prototype.getEngine = function () {
  24627. return this._engine;
  24628. };
  24629. /**
  24630. * Gets the total number of vertices rendered per frame
  24631. * @returns the total number of vertices rendered per frame
  24632. */
  24633. Scene.prototype.getTotalVertices = function () {
  24634. return this._totalVertices.current;
  24635. };
  24636. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24637. /**
  24638. * Gets the performance counter for total vertices
  24639. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24640. */
  24641. get: function () {
  24642. return this._totalVertices;
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. /**
  24648. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24649. * @returns the total number of active indices rendered per frame
  24650. */
  24651. Scene.prototype.getActiveIndices = function () {
  24652. return this._activeIndices.current;
  24653. };
  24654. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24655. /**
  24656. * Gets the performance counter for active indices
  24657. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24658. */
  24659. get: function () {
  24660. return this._activeIndices;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. /**
  24666. * Gets the total number of active particles rendered per frame
  24667. * @returns the total number of active particles rendered per frame
  24668. */
  24669. Scene.prototype.getActiveParticles = function () {
  24670. return this._activeParticles.current;
  24671. };
  24672. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24673. /**
  24674. * Gets the performance counter for active particles
  24675. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24676. */
  24677. get: function () {
  24678. return this._activeParticles;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. /**
  24684. * Gets the total number of active bones rendered per frame
  24685. * @returns the total number of active bones rendered per frame
  24686. */
  24687. Scene.prototype.getActiveBones = function () {
  24688. return this._activeBones.current;
  24689. };
  24690. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24691. /**
  24692. * Gets the performance counter for active bones
  24693. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24694. */
  24695. get: function () {
  24696. return this._activeBones;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. /** @hidden */
  24702. Scene.prototype.getInterFramePerfCounter = function () {
  24703. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24704. return 0;
  24705. };
  24706. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24707. /** @hidden */
  24708. get: function () {
  24709. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24710. return null;
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. /** @hidden */
  24716. Scene.prototype.getLastFrameDuration = function () {
  24717. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24718. return 0;
  24719. };
  24720. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24721. /** @hidden */
  24722. get: function () {
  24723. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24724. return null;
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. /** @hidden */
  24730. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24731. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24732. return 0;
  24733. };
  24734. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24735. /** @hidden */
  24736. get: function () {
  24737. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24738. return null;
  24739. },
  24740. enumerable: true,
  24741. configurable: true
  24742. });
  24743. /**
  24744. * Gets the array of active meshes
  24745. * @returns an array of AbstractMesh
  24746. */
  24747. Scene.prototype.getActiveMeshes = function () {
  24748. return this._activeMeshes;
  24749. };
  24750. /** @hidden */
  24751. Scene.prototype.getRenderTargetsDuration = function () {
  24752. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24753. return 0;
  24754. };
  24755. /** @hidden */
  24756. Scene.prototype.getRenderDuration = function () {
  24757. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24758. return 0;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24761. /** @hidden */
  24762. get: function () {
  24763. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24764. return null;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. /** @hidden */
  24770. Scene.prototype.getParticlesDuration = function () {
  24771. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24772. return 0;
  24773. };
  24774. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24775. /** @hidden */
  24776. get: function () {
  24777. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24778. return null;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. /** @hidden */
  24784. Scene.prototype.getSpritesDuration = function () {
  24785. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24786. return 0;
  24787. };
  24788. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24789. /** @hidden */
  24790. get: function () {
  24791. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24792. return null;
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. /**
  24798. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24799. * @returns a number
  24800. */
  24801. Scene.prototype.getAnimationRatio = function () {
  24802. return this._animationRatio;
  24803. };
  24804. /**
  24805. * Gets an unique Id for the current frame
  24806. * @returns a number
  24807. */
  24808. Scene.prototype.getRenderId = function () {
  24809. return this._renderId;
  24810. };
  24811. /** Call this function if you want to manually increment the render Id*/
  24812. Scene.prototype.incrementRenderId = function () {
  24813. this._renderId++;
  24814. };
  24815. Scene.prototype._updatePointerPosition = function (evt) {
  24816. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24817. if (!canvasRect) {
  24818. return;
  24819. }
  24820. this._pointerX = evt.clientX - canvasRect.left;
  24821. this._pointerY = evt.clientY - canvasRect.top;
  24822. this._unTranslatedPointerX = this._pointerX;
  24823. this._unTranslatedPointerY = this._pointerY;
  24824. };
  24825. Scene.prototype._createUbo = function () {
  24826. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24827. this._sceneUbo.addUniform("viewProjection", 16);
  24828. this._sceneUbo.addUniform("view", 16);
  24829. };
  24830. Scene.prototype._createAlternateUbo = function () {
  24831. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24832. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24833. this._alternateSceneUbo.addUniform("view", 16);
  24834. };
  24835. // Pointers handling
  24836. /**
  24837. * Use this method to simulate a pointer move on a mesh
  24838. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24839. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24840. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24841. * @returns the current scene
  24842. */
  24843. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24844. var evt = new PointerEvent("pointermove", pointerEventInit);
  24845. return this._processPointerMove(pickResult, evt);
  24846. };
  24847. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24848. var canvas = this._engine.getRenderingCanvas();
  24849. if (!canvas) {
  24850. return this;
  24851. }
  24852. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24853. this.setPointerOverSprite(null);
  24854. this.setPointerOverMesh(pickResult.pickedMesh);
  24855. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24856. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24857. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24858. }
  24859. else {
  24860. canvas.style.cursor = this.hoverCursor;
  24861. }
  24862. }
  24863. else {
  24864. canvas.style.cursor = this.defaultCursor;
  24865. }
  24866. }
  24867. else {
  24868. this.setPointerOverMesh(null);
  24869. // Sprites
  24870. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24871. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24872. this.setPointerOverSprite(pickResult.pickedSprite);
  24873. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24874. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24875. }
  24876. else {
  24877. canvas.style.cursor = this.hoverCursor;
  24878. }
  24879. }
  24880. else {
  24881. this.setPointerOverSprite(null);
  24882. // Restore pointer
  24883. canvas.style.cursor = this.defaultCursor;
  24884. }
  24885. }
  24886. if (pickResult) {
  24887. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24888. if (this.onPointerMove) {
  24889. this.onPointerMove(evt, pickResult, type);
  24890. }
  24891. if (this.onPointerObservable.hasObservers()) {
  24892. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24893. this.onPointerObservable.notifyObservers(pi, type);
  24894. }
  24895. }
  24896. return this;
  24897. };
  24898. /**
  24899. * Use this method to simulate a pointer down on a mesh
  24900. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24901. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24902. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24903. * @returns the current scene
  24904. */
  24905. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24906. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24907. return this._processPointerDown(pickResult, evt);
  24908. };
  24909. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24910. var _this = this;
  24911. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24912. this._pickedDownMesh = pickResult.pickedMesh;
  24913. var actionManager = pickResult.pickedMesh.actionManager;
  24914. if (actionManager) {
  24915. if (actionManager.hasPickTriggers) {
  24916. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24917. switch (evt.button) {
  24918. case 0:
  24919. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24920. break;
  24921. case 1:
  24922. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24923. break;
  24924. case 2:
  24925. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24926. break;
  24927. }
  24928. }
  24929. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24930. window.setTimeout(function () {
  24931. 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);
  24932. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24933. if (_this._totalPointersPressed !== 0 &&
  24934. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24935. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24936. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24937. _this._startingPointerTime = 0;
  24938. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24939. }
  24940. }
  24941. }, Scene.LongPressDelay);
  24942. }
  24943. }
  24944. }
  24945. if (pickResult) {
  24946. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24947. if (this.onPointerDown) {
  24948. this.onPointerDown(evt, pickResult, type);
  24949. }
  24950. if (this.onPointerObservable.hasObservers()) {
  24951. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24952. this.onPointerObservable.notifyObservers(pi, type);
  24953. }
  24954. }
  24955. return this;
  24956. };
  24957. /**
  24958. * Use this method to simulate a pointer up on a mesh
  24959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24960. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24961. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24962. * @returns the current scene
  24963. */
  24964. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24965. var evt = new PointerEvent("pointerup", pointerEventInit);
  24966. var clickInfo = new ClickInfo();
  24967. clickInfo.singleClick = true;
  24968. clickInfo.ignore = true;
  24969. return this._processPointerUp(pickResult, evt, clickInfo);
  24970. };
  24971. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24972. if (pickResult && pickResult && pickResult.pickedMesh) {
  24973. this._pickedUpMesh = pickResult.pickedMesh;
  24974. if (this._pickedDownMesh === this._pickedUpMesh) {
  24975. if (this.onPointerPick) {
  24976. this.onPointerPick(evt, pickResult);
  24977. }
  24978. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24979. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24980. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24981. this.onPointerObservable.notifyObservers(pi, type_1);
  24982. }
  24983. }
  24984. if (pickResult.pickedMesh.actionManager) {
  24985. if (clickInfo.ignore) {
  24986. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24987. }
  24988. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24990. }
  24991. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24992. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24993. }
  24994. }
  24995. }
  24996. if (this._pickedDownMesh &&
  24997. this._pickedDownMesh.actionManager &&
  24998. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24999. this._pickedDownMesh !== this._pickedUpMesh) {
  25000. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25001. }
  25002. var type = BABYLON.PointerEventTypes.POINTERUP;
  25003. if (this.onPointerObservable.hasObservers()) {
  25004. if (!clickInfo.ignore) {
  25005. if (!clickInfo.hasSwiped) {
  25006. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25007. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25008. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25009. this.onPointerObservable.notifyObservers(pi, type_2);
  25010. }
  25011. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25012. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25013. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25014. this.onPointerObservable.notifyObservers(pi, type_3);
  25015. }
  25016. }
  25017. }
  25018. else {
  25019. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25020. this.onPointerObservable.notifyObservers(pi, type);
  25021. }
  25022. }
  25023. if (this.onPointerUp) {
  25024. this.onPointerUp(evt, pickResult, type);
  25025. }
  25026. return this;
  25027. };
  25028. /**
  25029. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25030. * @param attachUp defines if you want to attach events to pointerup
  25031. * @param attachDown defines if you want to attach events to pointerdown
  25032. * @param attachMove defines if you want to attach events to pointermove
  25033. */
  25034. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25035. var _this = this;
  25036. if (attachUp === void 0) { attachUp = true; }
  25037. if (attachDown === void 0) { attachDown = true; }
  25038. if (attachMove === void 0) { attachMove = true; }
  25039. this._initActionManager = function (act, clickInfo) {
  25040. if (!_this._meshPickProceed) {
  25041. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25042. _this._currentPickResult = pickResult;
  25043. if (pickResult) {
  25044. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25045. }
  25046. _this._meshPickProceed = true;
  25047. }
  25048. return act;
  25049. };
  25050. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25051. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25052. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25053. btn !== _this._previousButtonPressed) {
  25054. _this._doubleClickOccured = false;
  25055. clickInfo.singleClick = true;
  25056. clickInfo.ignore = false;
  25057. cb(clickInfo, _this._currentPickResult);
  25058. }
  25059. };
  25060. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25061. var clickInfo = new ClickInfo();
  25062. _this._currentPickResult = null;
  25063. var act = null;
  25064. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25065. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25066. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25067. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25068. act = _this._initActionManager(act, clickInfo);
  25069. if (act)
  25070. checkPicking = act.hasPickTriggers;
  25071. }
  25072. if (checkPicking) {
  25073. var btn = evt.button;
  25074. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25075. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25076. if (!clickInfo.hasSwiped) {
  25077. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25078. if (!checkSingleClickImmediately) {
  25079. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25080. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25081. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25082. act = _this._initActionManager(act, clickInfo);
  25083. if (act)
  25084. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25085. }
  25086. }
  25087. if (checkSingleClickImmediately) {
  25088. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25089. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25090. btn !== _this._previousButtonPressed) {
  25091. clickInfo.singleClick = true;
  25092. cb(clickInfo, _this._currentPickResult);
  25093. }
  25094. }
  25095. // at least one double click is required to be check and exclusive double click is enabled
  25096. else {
  25097. // wait that no double click has been raised during the double click delay
  25098. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25099. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25100. }
  25101. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25102. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25103. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25104. act = _this._initActionManager(act, clickInfo);
  25105. if (act)
  25106. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25107. }
  25108. if (checkDoubleClick) {
  25109. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25110. if (btn === _this._previousButtonPressed &&
  25111. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25112. !_this._doubleClickOccured) {
  25113. // pointer has not moved for 2 clicks, it's a double click
  25114. if (!clickInfo.hasSwiped &&
  25115. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25116. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25117. _this._previousStartingPointerTime = 0;
  25118. _this._doubleClickOccured = true;
  25119. clickInfo.doubleClick = true;
  25120. clickInfo.ignore = false;
  25121. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25122. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25123. }
  25124. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25125. cb(clickInfo, _this._currentPickResult);
  25126. }
  25127. // if the two successive clicks are too far, it's just two simple clicks
  25128. else {
  25129. _this._doubleClickOccured = false;
  25130. _this._previousStartingPointerTime = _this._startingPointerTime;
  25131. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25132. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25133. _this._previousButtonPressed = btn;
  25134. if (Scene.ExclusiveDoubleClickMode) {
  25135. if (_this._previousDelayedSimpleClickTimeout) {
  25136. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25137. }
  25138. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25139. cb(clickInfo, _this._previousPickResult);
  25140. }
  25141. else {
  25142. cb(clickInfo, _this._currentPickResult);
  25143. }
  25144. }
  25145. }
  25146. // just the first click of the double has been raised
  25147. else {
  25148. _this._doubleClickOccured = false;
  25149. _this._previousStartingPointerTime = _this._startingPointerTime;
  25150. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25151. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25152. _this._previousButtonPressed = btn;
  25153. }
  25154. }
  25155. }
  25156. }
  25157. clickInfo.ignore = true;
  25158. cb(clickInfo, _this._currentPickResult);
  25159. };
  25160. this._spritePredicate = function (sprite) {
  25161. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25162. };
  25163. this._onPointerMove = function (evt) {
  25164. _this._updatePointerPosition(evt);
  25165. // PreObservable support
  25166. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25167. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25168. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25169. _this.onPrePointerObservable.notifyObservers(pi, type);
  25170. if (pi.skipOnPointerObservable) {
  25171. return;
  25172. }
  25173. }
  25174. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25175. return;
  25176. }
  25177. if (!_this.pointerMovePredicate) {
  25178. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25179. }
  25180. // Meshes
  25181. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25182. _this._processPointerMove(pickResult, evt);
  25183. };
  25184. this._onPointerDown = function (evt) {
  25185. _this._totalPointersPressed++;
  25186. _this._pickedDownMesh = null;
  25187. _this._meshPickProceed = false;
  25188. _this._updatePointerPosition(evt);
  25189. if (_this.preventDefaultOnPointerDown && canvas) {
  25190. evt.preventDefault();
  25191. canvas.focus();
  25192. }
  25193. // PreObservable support
  25194. if (_this.onPrePointerObservable.hasObservers()) {
  25195. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25196. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25197. _this.onPrePointerObservable.notifyObservers(pi, type);
  25198. if (pi.skipOnPointerObservable) {
  25199. return;
  25200. }
  25201. }
  25202. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25203. return;
  25204. }
  25205. _this._pointerCaptures[evt.pointerId] = true;
  25206. _this._startingPointerPosition.x = _this._pointerX;
  25207. _this._startingPointerPosition.y = _this._pointerY;
  25208. _this._startingPointerTime = Date.now();
  25209. if (!_this.pointerDownPredicate) {
  25210. _this.pointerDownPredicate = function (mesh) {
  25211. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25212. };
  25213. }
  25214. // Meshes
  25215. _this._pickedDownMesh = null;
  25216. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25217. _this._processPointerDown(pickResult, evt);
  25218. // Sprites
  25219. _this._pickedDownSprite = null;
  25220. if (_this.spriteManagers.length > 0) {
  25221. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25222. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25223. if (pickResult.pickedSprite.actionManager) {
  25224. _this._pickedDownSprite = pickResult.pickedSprite;
  25225. switch (evt.button) {
  25226. case 0:
  25227. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25228. break;
  25229. case 1:
  25230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25231. break;
  25232. case 2:
  25233. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25234. break;
  25235. }
  25236. if (pickResult.pickedSprite.actionManager) {
  25237. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25238. }
  25239. }
  25240. }
  25241. }
  25242. };
  25243. this._onPointerUp = function (evt) {
  25244. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25245. return; // So we need to test it the pointer down was pressed before.
  25246. }
  25247. _this._totalPointersPressed--;
  25248. _this._pickedUpMesh = null;
  25249. _this._meshPickProceed = false;
  25250. _this._updatePointerPosition(evt);
  25251. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25252. // PreObservable support
  25253. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25254. if (!clickInfo.ignore) {
  25255. if (!clickInfo.hasSwiped) {
  25256. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25257. var type = BABYLON.PointerEventTypes.POINTERTAP;
  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 (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25265. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25266. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25267. _this.onPrePointerObservable.notifyObservers(pi, type);
  25268. if (pi.skipOnPointerObservable) {
  25269. return;
  25270. }
  25271. }
  25272. }
  25273. }
  25274. else {
  25275. var type = BABYLON.PointerEventTypes.POINTERUP;
  25276. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25277. _this.onPrePointerObservable.notifyObservers(pi, type);
  25278. if (pi.skipOnPointerObservable) {
  25279. return;
  25280. }
  25281. }
  25282. }
  25283. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25284. return;
  25285. }
  25286. _this._pointerCaptures[evt.pointerId] = false;
  25287. if (!_this.pointerUpPredicate) {
  25288. _this.pointerUpPredicate = function (mesh) {
  25289. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25290. };
  25291. }
  25292. // Meshes
  25293. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25294. _this._initActionManager(null, clickInfo);
  25295. }
  25296. if (!pickResult) {
  25297. pickResult = _this._currentPickResult;
  25298. }
  25299. _this._processPointerUp(pickResult, evt, clickInfo);
  25300. // Sprites
  25301. if (!clickInfo.ignore) {
  25302. if (_this.spriteManagers.length > 0) {
  25303. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25304. if (spritePickResult) {
  25305. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25306. if (spritePickResult.pickedSprite.actionManager) {
  25307. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25308. if (spritePickResult.pickedSprite.actionManager) {
  25309. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25310. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25311. }
  25312. }
  25313. }
  25314. }
  25315. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25316. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25317. }
  25318. }
  25319. }
  25320. }
  25321. _this._previousPickResult = _this._currentPickResult;
  25322. });
  25323. };
  25324. this._onKeyDown = function (evt) {
  25325. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25326. if (_this.onPreKeyboardObservable.hasObservers()) {
  25327. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25328. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25329. if (pi.skipOnPointerObservable) {
  25330. return;
  25331. }
  25332. }
  25333. if (_this.onKeyboardObservable.hasObservers()) {
  25334. var pi = new BABYLON.KeyboardInfo(type, evt);
  25335. _this.onKeyboardObservable.notifyObservers(pi, type);
  25336. }
  25337. if (_this.actionManager) {
  25338. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25339. }
  25340. };
  25341. this._onKeyUp = function (evt) {
  25342. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25343. if (_this.onPreKeyboardObservable.hasObservers()) {
  25344. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25345. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25346. if (pi.skipOnPointerObservable) {
  25347. return;
  25348. }
  25349. }
  25350. if (_this.onKeyboardObservable.hasObservers()) {
  25351. var pi = new BABYLON.KeyboardInfo(type, evt);
  25352. _this.onKeyboardObservable.notifyObservers(pi, type);
  25353. }
  25354. if (_this.actionManager) {
  25355. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25356. }
  25357. };
  25358. var engine = this.getEngine();
  25359. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25360. if (!canvas) {
  25361. return;
  25362. }
  25363. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25364. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25365. });
  25366. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25367. if (!canvas) {
  25368. return;
  25369. }
  25370. canvas.removeEventListener("keydown", _this._onKeyDown);
  25371. canvas.removeEventListener("keyup", _this._onKeyUp);
  25372. });
  25373. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25374. var canvas = this._engine.getRenderingCanvas();
  25375. if (!canvas) {
  25376. return;
  25377. }
  25378. if (attachMove) {
  25379. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25380. // Wheel
  25381. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25382. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25383. }
  25384. if (attachDown) {
  25385. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25386. }
  25387. if (attachUp) {
  25388. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25389. }
  25390. canvas.tabIndex = 1;
  25391. };
  25392. /** Detaches all event handlers*/
  25393. Scene.prototype.detachControl = function () {
  25394. var engine = this.getEngine();
  25395. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25396. var canvas = engine.getRenderingCanvas();
  25397. if (!canvas) {
  25398. return;
  25399. }
  25400. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25401. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25402. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25403. if (this._onCanvasBlurObserver) {
  25404. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25405. }
  25406. if (this._onCanvasFocusObserver) {
  25407. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25408. }
  25409. // Wheel
  25410. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25411. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25412. // Keyboard
  25413. canvas.removeEventListener("keydown", this._onKeyDown);
  25414. canvas.removeEventListener("keyup", this._onKeyUp);
  25415. // Observables
  25416. this.onKeyboardObservable.clear();
  25417. this.onPreKeyboardObservable.clear();
  25418. this.onPointerObservable.clear();
  25419. this.onPrePointerObservable.clear();
  25420. };
  25421. /**
  25422. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25423. * Delay loaded resources are not taking in account
  25424. * @return true if all required resources are ready
  25425. */
  25426. Scene.prototype.isReady = function () {
  25427. if (this._isDisposed) {
  25428. return false;
  25429. }
  25430. if (this._pendingData.length > 0) {
  25431. return false;
  25432. }
  25433. var index;
  25434. var engine = this.getEngine();
  25435. // Geometries
  25436. for (index = 0; index < this._geometries.length; index++) {
  25437. var geometry = this._geometries[index];
  25438. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25439. return false;
  25440. }
  25441. }
  25442. // Meshes
  25443. for (index = 0; index < this.meshes.length; index++) {
  25444. var mesh = this.meshes[index];
  25445. if (!mesh.isEnabled()) {
  25446. continue;
  25447. }
  25448. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25449. continue;
  25450. }
  25451. if (!mesh.isReady(true)) {
  25452. return false;
  25453. }
  25454. // Effect layers
  25455. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25456. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25457. var layer = _a[_i];
  25458. if (!layer.hasMesh(mesh)) {
  25459. continue;
  25460. }
  25461. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25462. var subMesh = _c[_b];
  25463. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25464. return false;
  25465. }
  25466. }
  25467. }
  25468. }
  25469. // Post-processes
  25470. if (this.activeCameras && this.activeCameras.length > 0) {
  25471. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25472. var camera = _e[_d];
  25473. if (!camera.isReady(true)) {
  25474. return false;
  25475. }
  25476. }
  25477. }
  25478. else if (this.activeCamera) {
  25479. if (!this.activeCamera.isReady(true)) {
  25480. return false;
  25481. }
  25482. }
  25483. // Particles
  25484. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25485. var particleSystem = _g[_f];
  25486. if (!particleSystem.isReady()) {
  25487. return false;
  25488. }
  25489. }
  25490. return true;
  25491. };
  25492. /** Resets all cached information relative to material (including effect and visibility) */
  25493. Scene.prototype.resetCachedMaterial = function () {
  25494. this._cachedMaterial = null;
  25495. this._cachedEffect = null;
  25496. this._cachedVisibility = null;
  25497. };
  25498. /**
  25499. * Registers a function to be called before every frame render
  25500. * @param func defines the function to register
  25501. */
  25502. Scene.prototype.registerBeforeRender = function (func) {
  25503. this.onBeforeRenderObservable.add(func);
  25504. };
  25505. /**
  25506. * Unregisters a function called before every frame render
  25507. * @param func defines the function to unregister
  25508. */
  25509. Scene.prototype.unregisterBeforeRender = function (func) {
  25510. this.onBeforeRenderObservable.removeCallback(func);
  25511. };
  25512. /**
  25513. * Registers a function to be called after every frame render
  25514. * @param func defines the function to register
  25515. */
  25516. Scene.prototype.registerAfterRender = function (func) {
  25517. this.onAfterRenderObservable.add(func);
  25518. };
  25519. /**
  25520. * Unregisters a function called after every frame render
  25521. * @param func defines the function to unregister
  25522. */
  25523. Scene.prototype.unregisterAfterRender = function (func) {
  25524. this.onAfterRenderObservable.removeCallback(func);
  25525. };
  25526. Scene.prototype._executeOnceBeforeRender = function (func) {
  25527. var _this = this;
  25528. var execFunc = function () {
  25529. func();
  25530. setTimeout(function () {
  25531. _this.unregisterBeforeRender(execFunc);
  25532. });
  25533. };
  25534. this.registerBeforeRender(execFunc);
  25535. };
  25536. /**
  25537. * The provided function will run before render once and will be disposed afterwards.
  25538. * A timeout delay can be provided so that the function will be executed in N ms.
  25539. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25540. * @param func The function to be executed.
  25541. * @param timeout optional delay in ms
  25542. */
  25543. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25544. var _this = this;
  25545. if (timeout !== undefined) {
  25546. setTimeout(function () {
  25547. _this._executeOnceBeforeRender(func);
  25548. }, timeout);
  25549. }
  25550. else {
  25551. this._executeOnceBeforeRender(func);
  25552. }
  25553. };
  25554. /** @hidden */
  25555. Scene.prototype._addPendingData = function (data) {
  25556. this._pendingData.push(data);
  25557. };
  25558. /** @hidden */
  25559. Scene.prototype._removePendingData = function (data) {
  25560. var wasLoading = this.isLoading;
  25561. var index = this._pendingData.indexOf(data);
  25562. if (index !== -1) {
  25563. this._pendingData.splice(index, 1);
  25564. }
  25565. if (wasLoading && !this.isLoading) {
  25566. this.onDataLoadedObservable.notifyObservers(this);
  25567. }
  25568. };
  25569. /**
  25570. * Returns the number of items waiting to be loaded
  25571. * @returns the number of items waiting to be loaded
  25572. */
  25573. Scene.prototype.getWaitingItemsCount = function () {
  25574. return this._pendingData.length;
  25575. };
  25576. Object.defineProperty(Scene.prototype, "isLoading", {
  25577. /**
  25578. * Returns a boolean indicating if the scene is still loading data
  25579. */
  25580. get: function () {
  25581. return this._pendingData.length > 0;
  25582. },
  25583. enumerable: true,
  25584. configurable: true
  25585. });
  25586. /**
  25587. * Registers a function to be executed when the scene is ready
  25588. * @param {Function} func - the function to be executed
  25589. */
  25590. Scene.prototype.executeWhenReady = function (func) {
  25591. var _this = this;
  25592. this.onReadyObservable.add(func);
  25593. if (this._executeWhenReadyTimeoutId !== -1) {
  25594. return;
  25595. }
  25596. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25597. _this._checkIsReady();
  25598. }, 150);
  25599. };
  25600. /**
  25601. * Returns a promise that resolves when the scene is ready
  25602. * @returns A promise that resolves when the scene is ready
  25603. */
  25604. Scene.prototype.whenReadyAsync = function () {
  25605. var _this = this;
  25606. return new Promise(function (resolve) {
  25607. _this.executeWhenReady(function () {
  25608. resolve();
  25609. });
  25610. });
  25611. };
  25612. /** @hidden */
  25613. Scene.prototype._checkIsReady = function () {
  25614. var _this = this;
  25615. if (this.isReady()) {
  25616. this.onReadyObservable.notifyObservers(this);
  25617. this.onReadyObservable.clear();
  25618. this._executeWhenReadyTimeoutId = -1;
  25619. return;
  25620. }
  25621. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25622. _this._checkIsReady();
  25623. }, 150);
  25624. };
  25625. // Animations
  25626. /**
  25627. * Will start the animation sequence of a given target
  25628. * @param target defines the target
  25629. * @param from defines from which frame should animation start
  25630. * @param to defines until which frame should animation run.
  25631. * @param weight defines the weight to apply to the animation (1.0 by default)
  25632. * @param loop defines if the animation loops
  25633. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25634. * @param onAnimationEnd defines the function to be executed when the animation ends
  25635. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25636. * @returns the animatable object created for this animation
  25637. */
  25638. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25639. if (weight === void 0) { weight = 1.0; }
  25640. if (speedRatio === void 0) { speedRatio = 1.0; }
  25641. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25642. returnedAnimatable.weight = weight;
  25643. return returnedAnimatable;
  25644. };
  25645. /**
  25646. * Will start the animation sequence of a given target
  25647. * @param target defines the target
  25648. * @param from defines from which frame should animation start
  25649. * @param to defines until which frame should animation run.
  25650. * @param loop defines if the animation loops
  25651. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25652. * @param onAnimationEnd defines the function to be executed when the animation ends
  25653. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25654. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25655. * @returns the animatable object created for this animation
  25656. */
  25657. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25658. if (speedRatio === void 0) { speedRatio = 1.0; }
  25659. if (stopCurrent === void 0) { stopCurrent = true; }
  25660. if (from > to && speedRatio > 0) {
  25661. speedRatio *= -1;
  25662. }
  25663. if (stopCurrent) {
  25664. this.stopAnimation(target);
  25665. }
  25666. if (!animatable) {
  25667. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25668. }
  25669. // Local animations
  25670. if (target.animations) {
  25671. animatable.appendAnimations(target, target.animations);
  25672. }
  25673. // Children animations
  25674. if (target.getAnimatables) {
  25675. var animatables = target.getAnimatables();
  25676. for (var index = 0; index < animatables.length; index++) {
  25677. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25678. }
  25679. }
  25680. animatable.reset();
  25681. return animatable;
  25682. };
  25683. /**
  25684. * Begin a new animation on a given node
  25685. * @param target defines the target where the animation will take place
  25686. * @param animations defines the list of animations to start
  25687. * @param from defines the initial value
  25688. * @param to defines the final value
  25689. * @param loop defines if you want animation to loop (off by default)
  25690. * @param speedRatio defines the speed ratio to apply to all animations
  25691. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25692. * @returns the list of created animatables
  25693. */
  25694. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25695. if (speedRatio === undefined) {
  25696. speedRatio = 1.0;
  25697. }
  25698. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25699. return animatable;
  25700. };
  25701. /**
  25702. * Begin a new animation on a given node and its hierarchy
  25703. * @param target defines the root node where the animation will take place
  25704. * @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.
  25705. * @param animations defines the list of animations to start
  25706. * @param from defines the initial value
  25707. * @param to defines the final value
  25708. * @param loop defines if you want animation to loop (off by default)
  25709. * @param speedRatio defines the speed ratio to apply to all animations
  25710. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25711. * @returns the list of animatables created for all nodes
  25712. */
  25713. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25714. var children = target.getDescendants(directDescendantsOnly);
  25715. var result = [];
  25716. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25717. var child = children_1[_i];
  25718. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25719. }
  25720. return result;
  25721. };
  25722. /**
  25723. * Gets the animatable associated with a specific target
  25724. * @param target defines the target of the animatable
  25725. * @returns the required animatable if found
  25726. */
  25727. Scene.prototype.getAnimatableByTarget = function (target) {
  25728. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25729. if (this._activeAnimatables[index].target === target) {
  25730. return this._activeAnimatables[index];
  25731. }
  25732. }
  25733. return null;
  25734. };
  25735. /**
  25736. * Gets all animatables associated with a given target
  25737. * @param target defines the target to look animatables for
  25738. * @returns an array of Animatables
  25739. */
  25740. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25741. var result = [];
  25742. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25743. if (this._activeAnimatables[index].target === target) {
  25744. result.push(this._activeAnimatables[index]);
  25745. }
  25746. }
  25747. return result;
  25748. };
  25749. Object.defineProperty(Scene.prototype, "animatables", {
  25750. /**
  25751. * Gets all animatable attached to the scene
  25752. */
  25753. get: function () {
  25754. return this._activeAnimatables;
  25755. },
  25756. enumerable: true,
  25757. configurable: true
  25758. });
  25759. /**
  25760. * Will stop the animation of the given target
  25761. * @param target - the target
  25762. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25763. */
  25764. Scene.prototype.stopAnimation = function (target, animationName) {
  25765. var animatables = this.getAllAnimatablesByTarget(target);
  25766. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25767. var animatable = animatables_1[_i];
  25768. animatable.stop(animationName);
  25769. }
  25770. };
  25771. /**
  25772. * Stops and removes all animations that have been applied to the scene
  25773. */
  25774. Scene.prototype.stopAllAnimations = function () {
  25775. if (this._activeAnimatables) {
  25776. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25777. this._activeAnimatables[i].stop();
  25778. }
  25779. this._activeAnimatables = [];
  25780. }
  25781. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25782. var group = _a[_i];
  25783. group.stop();
  25784. }
  25785. };
  25786. Scene.prototype._animate = function () {
  25787. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25788. return;
  25789. }
  25790. // Getting time
  25791. var now = BABYLON.Tools.Now;
  25792. if (!this._animationTimeLast) {
  25793. if (this._pendingData.length > 0) {
  25794. return;
  25795. }
  25796. this._animationTimeLast = now;
  25797. }
  25798. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25799. this._animationTime += deltaTime;
  25800. this._animationTimeLast = now;
  25801. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25802. this._activeAnimatables[index]._animate(this._animationTime);
  25803. }
  25804. // Late animation bindings
  25805. this._processLateAnimationBindings();
  25806. };
  25807. /** @hidden */
  25808. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25809. var target = runtimeAnimation.target;
  25810. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25811. if (!target._lateAnimationHolders) {
  25812. target._lateAnimationHolders = {};
  25813. }
  25814. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25815. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25816. totalWeight: 0,
  25817. animations: [],
  25818. originalValue: originalValue
  25819. };
  25820. }
  25821. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25822. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25823. };
  25824. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25825. var normalizer = 1.0;
  25826. var finalPosition = BABYLON.Tmp.Vector3[0];
  25827. var finalScaling = BABYLON.Tmp.Vector3[1];
  25828. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25829. var startIndex = 0;
  25830. var originalAnimation = holder.animations[0];
  25831. var originalValue = holder.originalValue;
  25832. var scale = 1;
  25833. if (holder.totalWeight < 1.0) {
  25834. // We need to mix the original value in
  25835. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25836. scale = 1.0 - holder.totalWeight;
  25837. }
  25838. else {
  25839. startIndex = 1;
  25840. // We need to normalize the weights
  25841. normalizer = holder.totalWeight;
  25842. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25843. scale = originalAnimation.weight / normalizer;
  25844. if (scale == 1) {
  25845. return originalAnimation.currentValue;
  25846. }
  25847. }
  25848. finalScaling.scaleInPlace(scale);
  25849. finalPosition.scaleInPlace(scale);
  25850. finalQuaternion.scaleInPlace(scale);
  25851. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25852. var runtimeAnimation = holder.animations[animIndex];
  25853. var scale = runtimeAnimation.weight / normalizer;
  25854. var currentPosition = BABYLON.Tmp.Vector3[2];
  25855. var currentScaling = BABYLON.Tmp.Vector3[3];
  25856. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25857. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25858. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25859. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25860. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25861. }
  25862. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25863. return originalAnimation._workValue;
  25864. };
  25865. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25866. var originalAnimation = holder.animations[0];
  25867. var originalValue = holder.originalValue;
  25868. if (holder.animations.length === 1) {
  25869. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25870. }
  25871. var normalizer = 1.0;
  25872. var quaternions;
  25873. var weights;
  25874. if (holder.totalWeight < 1.0) {
  25875. var scale = 1.0 - holder.totalWeight;
  25876. quaternions = [];
  25877. weights = [];
  25878. quaternions.push(originalValue);
  25879. weights.push(scale);
  25880. }
  25881. else {
  25882. if (holder.animations.length === 2) { // Slerp as soon as we can
  25883. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25884. }
  25885. quaternions = [];
  25886. weights = [];
  25887. normalizer = holder.totalWeight;
  25888. }
  25889. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25890. var runtimeAnimation = holder.animations[animIndex];
  25891. quaternions.push(runtimeAnimation.currentValue);
  25892. weights.push(runtimeAnimation.weight / normalizer);
  25893. }
  25894. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25895. var cumulativeAmount = 0;
  25896. var cumulativeQuaternion = null;
  25897. for (var index = 0; index < quaternions.length;) {
  25898. if (!cumulativeQuaternion) {
  25899. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25900. cumulativeAmount = weights[index] + weights[index + 1];
  25901. index += 2;
  25902. continue;
  25903. }
  25904. cumulativeAmount += weights[index];
  25905. cumulativeQuaternion = BABYLON.Quaternion.Slerp(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount);
  25906. index++;
  25907. }
  25908. return cumulativeQuaternion;
  25909. };
  25910. Scene.prototype._processLateAnimationBindings = function () {
  25911. if (!this._registeredForLateAnimationBindings.length) {
  25912. return;
  25913. }
  25914. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25915. var target = this._registeredForLateAnimationBindings.data[index];
  25916. for (var path in target._lateAnimationHolders) {
  25917. var holder = target._lateAnimationHolders[path];
  25918. var originalAnimation = holder.animations[0];
  25919. var originalValue = holder.originalValue;
  25920. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25921. var finalValue = void 0;
  25922. if (matrixDecomposeMode) {
  25923. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25924. }
  25925. else {
  25926. var quaternionMode = originalValue.w !== undefined;
  25927. if (quaternionMode) {
  25928. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25929. }
  25930. else {
  25931. var startIndex = 0;
  25932. var normalizer = 1.0;
  25933. if (holder.totalWeight < 1.0) {
  25934. // We need to mix the original value in
  25935. if (originalValue.scale) {
  25936. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25937. }
  25938. else {
  25939. finalValue = originalValue * (1.0 - holder.totalWeight);
  25940. }
  25941. }
  25942. else {
  25943. // We need to normalize the weights
  25944. normalizer = holder.totalWeight;
  25945. var scale_1 = originalAnimation.weight / normalizer;
  25946. if (scale_1 !== 1) {
  25947. if (originalAnimation.currentValue.scale) {
  25948. finalValue = originalAnimation.currentValue.scale(scale_1);
  25949. }
  25950. else {
  25951. finalValue = originalAnimation.currentValue * scale_1;
  25952. }
  25953. }
  25954. else {
  25955. finalValue = originalAnimation.currentValue;
  25956. }
  25957. startIndex = 1;
  25958. }
  25959. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25960. var runtimeAnimation = holder.animations[animIndex];
  25961. var scale = runtimeAnimation.weight / normalizer;
  25962. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25963. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25964. }
  25965. else {
  25966. finalValue += runtimeAnimation.currentValue * scale;
  25967. }
  25968. }
  25969. }
  25970. }
  25971. target[path] = finalValue;
  25972. }
  25973. target._lateAnimationHolders = {};
  25974. }
  25975. this._registeredForLateAnimationBindings.reset();
  25976. };
  25977. // Matrix
  25978. /** @hidden */
  25979. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25980. this._useAlternateCameraConfiguration = active;
  25981. };
  25982. /**
  25983. * Gets the current view matrix
  25984. * @returns a Matrix
  25985. */
  25986. Scene.prototype.getViewMatrix = function () {
  25987. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25988. };
  25989. /**
  25990. * Gets the current projection matrix
  25991. * @returns a Matrix
  25992. */
  25993. Scene.prototype.getProjectionMatrix = function () {
  25994. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25995. };
  25996. /**
  25997. * Gets the current transform matrix
  25998. * @returns a Matrix made of View * Projection
  25999. */
  26000. Scene.prototype.getTransformMatrix = function () {
  26001. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26002. };
  26003. /**
  26004. * Sets the current transform matrix
  26005. * @param view defines the View matrix to use
  26006. * @param projection defines the Projection matrix to use
  26007. */
  26008. Scene.prototype.setTransformMatrix = function (view, projection) {
  26009. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26010. return;
  26011. }
  26012. this._viewUpdateFlag = view.updateFlag;
  26013. this._projectionUpdateFlag = projection.updateFlag;
  26014. this._viewMatrix = view;
  26015. this._projectionMatrix = projection;
  26016. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26017. // Update frustum
  26018. if (!this._frustumPlanes) {
  26019. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26020. }
  26021. else {
  26022. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26023. }
  26024. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26025. var otherCamera = this.activeCamera._alternateCamera;
  26026. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26027. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26028. }
  26029. if (this._sceneUbo.useUbo) {
  26030. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26031. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26032. this._sceneUbo.update();
  26033. }
  26034. };
  26035. /** @hidden */
  26036. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26037. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26038. return;
  26039. }
  26040. this._alternateViewUpdateFlag = view.updateFlag;
  26041. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26042. this._alternateViewMatrix = view;
  26043. this._alternateProjectionMatrix = projection;
  26044. if (!this._alternateTransformMatrix) {
  26045. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26046. }
  26047. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26048. if (!this._alternateSceneUbo) {
  26049. this._createAlternateUbo();
  26050. }
  26051. if (this._alternateSceneUbo.useUbo) {
  26052. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26053. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26054. this._alternateSceneUbo.update();
  26055. }
  26056. };
  26057. /**
  26058. * Gets the uniform buffer used to store scene data
  26059. * @returns a UniformBuffer
  26060. */
  26061. Scene.prototype.getSceneUniformBuffer = function () {
  26062. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26063. };
  26064. /**
  26065. * Gets an unique (relatively to the current scene) Id
  26066. * @returns an unique number for the scene
  26067. */
  26068. Scene.prototype.getUniqueId = function () {
  26069. var result = Scene._uniqueIdCounter;
  26070. Scene._uniqueIdCounter++;
  26071. return result;
  26072. };
  26073. /**
  26074. * Add a mesh to the list of scene's meshes
  26075. * @param newMesh defines the mesh to add
  26076. */
  26077. Scene.prototype.addMesh = function (newMesh) {
  26078. this.meshes.push(newMesh);
  26079. //notify the collision coordinator
  26080. if (this.collisionCoordinator) {
  26081. this.collisionCoordinator.onMeshAdded(newMesh);
  26082. }
  26083. newMesh._resyncLightSources();
  26084. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26085. };
  26086. /**
  26087. * Remove a mesh for the list of scene's meshes
  26088. * @param toRemove defines the mesh to remove
  26089. * @param recursive if all child meshes should also be removed from the scene
  26090. * @returns the index where the mesh was in the mesh list
  26091. */
  26092. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26093. var _this = this;
  26094. if (recursive === void 0) { recursive = false; }
  26095. var index = this.meshes.indexOf(toRemove);
  26096. if (index !== -1) {
  26097. // Remove from the scene if mesh found
  26098. this.meshes.splice(index, 1);
  26099. }
  26100. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26101. if (recursive) {
  26102. toRemove.getChildMeshes().forEach(function (m) {
  26103. _this.removeMesh(m);
  26104. });
  26105. }
  26106. return index;
  26107. };
  26108. /**
  26109. * Add a transform node to the list of scene's transform nodes
  26110. * @param newTransformNode defines the transform node to add
  26111. */
  26112. Scene.prototype.addTransformNode = function (newTransformNode) {
  26113. this.transformNodes.push(newTransformNode);
  26114. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26115. };
  26116. /**
  26117. * Remove a transform node for the list of scene's transform nodes
  26118. * @param toRemove defines the transform node to remove
  26119. * @returns the index where the transform node was in the transform node list
  26120. */
  26121. Scene.prototype.removeTransformNode = function (toRemove) {
  26122. var index = this.transformNodes.indexOf(toRemove);
  26123. if (index !== -1) {
  26124. // Remove from the scene if found
  26125. this.transformNodes.splice(index, 1);
  26126. }
  26127. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26128. return index;
  26129. };
  26130. /**
  26131. * Remove a skeleton for the list of scene's skeletons
  26132. * @param toRemove defines the skeleton to remove
  26133. * @returns the index where the skeleton was in the skeleton list
  26134. */
  26135. Scene.prototype.removeSkeleton = function (toRemove) {
  26136. var index = this.skeletons.indexOf(toRemove);
  26137. if (index !== -1) {
  26138. // Remove from the scene if found
  26139. this.skeletons.splice(index, 1);
  26140. }
  26141. return index;
  26142. };
  26143. /**
  26144. * Remove a morph target for the list of scene's morph targets
  26145. * @param toRemove defines the morph target to remove
  26146. * @returns the index where the morph target was in the morph target list
  26147. */
  26148. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26149. var index = this.morphTargetManagers.indexOf(toRemove);
  26150. if (index !== -1) {
  26151. // Remove from the scene if found
  26152. this.morphTargetManagers.splice(index, 1);
  26153. }
  26154. return index;
  26155. };
  26156. /**
  26157. * Remove a light for the list of scene's lights
  26158. * @param toRemove defines the light to remove
  26159. * @returns the index where the light was in the light list
  26160. */
  26161. Scene.prototype.removeLight = function (toRemove) {
  26162. var index = this.lights.indexOf(toRemove);
  26163. if (index !== -1) {
  26164. // Remove from meshes
  26165. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26166. var mesh = _a[_i];
  26167. mesh._removeLightSource(toRemove);
  26168. }
  26169. // Remove from the scene if mesh found
  26170. this.lights.splice(index, 1);
  26171. this.sortLightsByPriority();
  26172. }
  26173. this.onLightRemovedObservable.notifyObservers(toRemove);
  26174. return index;
  26175. };
  26176. /**
  26177. * Remove a camera for the list of scene's cameras
  26178. * @param toRemove defines the camera to remove
  26179. * @returns the index where the camera was in the camera list
  26180. */
  26181. Scene.prototype.removeCamera = function (toRemove) {
  26182. var index = this.cameras.indexOf(toRemove);
  26183. if (index !== -1) {
  26184. // Remove from the scene if mesh found
  26185. this.cameras.splice(index, 1);
  26186. }
  26187. // Remove from activeCameras
  26188. var index2 = this.activeCameras.indexOf(toRemove);
  26189. if (index2 !== -1) {
  26190. // Remove from the scene if mesh found
  26191. this.activeCameras.splice(index2, 1);
  26192. }
  26193. // Reset the activeCamera
  26194. if (this.activeCamera === toRemove) {
  26195. if (this.cameras.length > 0) {
  26196. this.activeCamera = this.cameras[0];
  26197. }
  26198. else {
  26199. this.activeCamera = null;
  26200. }
  26201. }
  26202. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26203. return index;
  26204. };
  26205. /**
  26206. * Remove a particle system for the list of scene's particle systems
  26207. * @param toRemove defines the particle system to remove
  26208. * @returns the index where the particle system was in the particle system list
  26209. */
  26210. Scene.prototype.removeParticleSystem = function (toRemove) {
  26211. var index = this.particleSystems.indexOf(toRemove);
  26212. if (index !== -1) {
  26213. this.particleSystems.splice(index, 1);
  26214. }
  26215. return index;
  26216. };
  26217. /**
  26218. * Remove a animation for the list of scene's animations
  26219. * @param toRemove defines the animation to remove
  26220. * @returns the index where the animation was in the animation list
  26221. */
  26222. Scene.prototype.removeAnimation = function (toRemove) {
  26223. var index = this.animations.indexOf(toRemove);
  26224. if (index !== -1) {
  26225. this.animations.splice(index, 1);
  26226. }
  26227. return index;
  26228. };
  26229. /**
  26230. * Removes the given animation group from this scene.
  26231. * @param toRemove The animation group to remove
  26232. * @returns The index of the removed animation group
  26233. */
  26234. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26235. var index = this.animationGroups.indexOf(toRemove);
  26236. if (index !== -1) {
  26237. this.animationGroups.splice(index, 1);
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Removes the given multi-material from this scene.
  26243. * @param toRemove The multi-material to remove
  26244. * @returns The index of the removed multi-material
  26245. */
  26246. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26247. var index = this.multiMaterials.indexOf(toRemove);
  26248. if (index !== -1) {
  26249. this.multiMaterials.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Removes the given material from this scene.
  26255. * @param toRemove The material to remove
  26256. * @returns The index of the removed material
  26257. */
  26258. Scene.prototype.removeMaterial = function (toRemove) {
  26259. var index = this.materials.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. this.materials.splice(index, 1);
  26262. }
  26263. return index;
  26264. };
  26265. /**
  26266. * Removes the given lens flare system from this scene.
  26267. * @param toRemove The lens flare system to remove
  26268. * @returns The index of the removed lens flare system
  26269. */
  26270. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26271. var index = this.lensFlareSystems.indexOf(toRemove);
  26272. if (index !== -1) {
  26273. this.lensFlareSystems.splice(index, 1);
  26274. }
  26275. return index;
  26276. };
  26277. /**
  26278. * Removes the given action manager from this scene.
  26279. * @param toRemove The action manager to remove
  26280. * @returns The index of the removed action manager
  26281. */
  26282. Scene.prototype.removeActionManager = function (toRemove) {
  26283. var index = this._actionManagers.indexOf(toRemove);
  26284. if (index !== -1) {
  26285. this._actionManagers.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Removes the given effect layer from this scene.
  26291. * @param toRemove defines the effect layer to remove
  26292. * @returns the index of the removed effect layer
  26293. */
  26294. Scene.prototype.removeEffectLayer = function (toRemove) {
  26295. var index = this.effectLayers.indexOf(toRemove);
  26296. if (index !== -1) {
  26297. this.effectLayers.splice(index, 1);
  26298. }
  26299. return index;
  26300. };
  26301. /**
  26302. * Removes the given texture from this scene.
  26303. * @param toRemove The texture to remove
  26304. * @returns The index of the removed texture
  26305. */
  26306. Scene.prototype.removeTexture = function (toRemove) {
  26307. var index = this.textures.indexOf(toRemove);
  26308. if (index !== -1) {
  26309. this.textures.splice(index, 1);
  26310. }
  26311. return index;
  26312. };
  26313. /**
  26314. * Adds the given light to this scene
  26315. * @param newLight The light to add
  26316. */
  26317. Scene.prototype.addLight = function (newLight) {
  26318. this.lights.push(newLight);
  26319. this.sortLightsByPriority();
  26320. // Add light to all meshes (To support if the light is removed and then readded)
  26321. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26322. var mesh = _a[_i];
  26323. if (mesh._lightSources.indexOf(newLight) === -1) {
  26324. mesh._lightSources.push(newLight);
  26325. mesh._resyncLightSources();
  26326. }
  26327. }
  26328. this.onNewLightAddedObservable.notifyObservers(newLight);
  26329. };
  26330. /**
  26331. * Sorts the list list based on light priorities
  26332. */
  26333. Scene.prototype.sortLightsByPriority = function () {
  26334. if (this.requireLightSorting) {
  26335. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26336. }
  26337. };
  26338. /**
  26339. * Adds the given camera to this scene
  26340. * @param newCamera The camera to add
  26341. */
  26342. Scene.prototype.addCamera = function (newCamera) {
  26343. this.cameras.push(newCamera);
  26344. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26345. };
  26346. /**
  26347. * Adds the given skeleton to this scene
  26348. * @param newSkeleton The skeleton to add
  26349. */
  26350. Scene.prototype.addSkeleton = function (newSkeleton) {
  26351. this.skeletons.push(newSkeleton);
  26352. };
  26353. /**
  26354. * Adds the given particle system to this scene
  26355. * @param newParticleSystem The particle system to add
  26356. */
  26357. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26358. this.particleSystems.push(newParticleSystem);
  26359. };
  26360. /**
  26361. * Adds the given animation to this scene
  26362. * @param newAnimation The animation to add
  26363. */
  26364. Scene.prototype.addAnimation = function (newAnimation) {
  26365. this.animations.push(newAnimation);
  26366. };
  26367. /**
  26368. * Adds the given animation group to this scene.
  26369. * @param newAnimationGroup The animation group to add
  26370. */
  26371. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26372. this.animationGroups.push(newAnimationGroup);
  26373. };
  26374. /**
  26375. * Adds the given multi-material to this scene
  26376. * @param newMultiMaterial The multi-material to add
  26377. */
  26378. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26379. this.multiMaterials.push(newMultiMaterial);
  26380. };
  26381. /**
  26382. * Adds the given material to this scene
  26383. * @param newMaterial The material to add
  26384. */
  26385. Scene.prototype.addMaterial = function (newMaterial) {
  26386. this.materials.push(newMaterial);
  26387. };
  26388. /**
  26389. * Adds the given morph target to this scene
  26390. * @param newMorphTargetManager The morph target to add
  26391. */
  26392. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26393. this.morphTargetManagers.push(newMorphTargetManager);
  26394. };
  26395. /**
  26396. * Adds the given geometry to this scene
  26397. * @param newGeometry The geometry to add
  26398. */
  26399. Scene.prototype.addGeometry = function (newGeometry) {
  26400. this._geometries.push(newGeometry);
  26401. };
  26402. /**
  26403. * Adds the given lens flare system to this scene
  26404. * @param newLensFlareSystem The lens flare system to add
  26405. */
  26406. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26407. this.lensFlareSystems.push(newLensFlareSystem);
  26408. };
  26409. /**
  26410. * Adds the given effect layer to this scene
  26411. * @param newEffectLayer defines the effect layer to add
  26412. */
  26413. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26414. this.effectLayers.push(newEffectLayer);
  26415. };
  26416. /**
  26417. * Adds the given action manager to this scene
  26418. * @param newActionManager The action manager to add
  26419. */
  26420. Scene.prototype.addActionManager = function (newActionManager) {
  26421. this._actionManagers.push(newActionManager);
  26422. };
  26423. /**
  26424. * Adds the given texture to this scene.
  26425. * @param newTexture The texture to add
  26426. */
  26427. Scene.prototype.addTexture = function (newTexture) {
  26428. this.textures.push(newTexture);
  26429. };
  26430. /**
  26431. * Switch active camera
  26432. * @param newCamera defines the new active camera
  26433. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26434. */
  26435. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26436. if (attachControl === void 0) { attachControl = true; }
  26437. var canvas = this._engine.getRenderingCanvas();
  26438. if (!canvas) {
  26439. return;
  26440. }
  26441. if (this.activeCamera) {
  26442. this.activeCamera.detachControl(canvas);
  26443. }
  26444. this.activeCamera = newCamera;
  26445. if (attachControl) {
  26446. newCamera.attachControl(canvas);
  26447. }
  26448. };
  26449. /**
  26450. * sets the active camera of the scene using its ID
  26451. * @param id defines the camera's ID
  26452. * @return the new active camera or null if none found.
  26453. */
  26454. Scene.prototype.setActiveCameraByID = function (id) {
  26455. var camera = this.getCameraByID(id);
  26456. if (camera) {
  26457. this.activeCamera = camera;
  26458. return camera;
  26459. }
  26460. return null;
  26461. };
  26462. /**
  26463. * sets the active camera of the scene using its name
  26464. * @param name defines the camera's name
  26465. * @returns the new active camera or null if none found.
  26466. */
  26467. Scene.prototype.setActiveCameraByName = function (name) {
  26468. var camera = this.getCameraByName(name);
  26469. if (camera) {
  26470. this.activeCamera = camera;
  26471. return camera;
  26472. }
  26473. return null;
  26474. };
  26475. /**
  26476. * get an animation group using its name
  26477. * @param name defines the material's name
  26478. * @return the animation group or null if none found.
  26479. */
  26480. Scene.prototype.getAnimationGroupByName = function (name) {
  26481. for (var index = 0; index < this.animationGroups.length; index++) {
  26482. if (this.animationGroups[index].name === name) {
  26483. return this.animationGroups[index];
  26484. }
  26485. }
  26486. return null;
  26487. };
  26488. /**
  26489. * get a material using its id
  26490. * @param id defines the material's ID
  26491. * @return the material or null if none found.
  26492. */
  26493. Scene.prototype.getMaterialByID = function (id) {
  26494. for (var index = 0; index < this.materials.length; index++) {
  26495. if (this.materials[index].id === id) {
  26496. return this.materials[index];
  26497. }
  26498. }
  26499. return null;
  26500. };
  26501. /**
  26502. * Gets a material using its name
  26503. * @param name defines the material's name
  26504. * @return the material or null if none found.
  26505. */
  26506. Scene.prototype.getMaterialByName = function (name) {
  26507. for (var index = 0; index < this.materials.length; index++) {
  26508. if (this.materials[index].name === name) {
  26509. return this.materials[index];
  26510. }
  26511. }
  26512. return null;
  26513. };
  26514. /**
  26515. * Gets a lens flare system using its name
  26516. * @param name defines the name to look for
  26517. * @returns the lens flare system or null if not found
  26518. */
  26519. Scene.prototype.getLensFlareSystemByName = function (name) {
  26520. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26521. if (this.lensFlareSystems[index].name === name) {
  26522. return this.lensFlareSystems[index];
  26523. }
  26524. }
  26525. return null;
  26526. };
  26527. /**
  26528. * Gets a lens flare system using its id
  26529. * @param id defines the id to look for
  26530. * @returns the lens flare system or null if not found
  26531. */
  26532. Scene.prototype.getLensFlareSystemByID = function (id) {
  26533. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26534. if (this.lensFlareSystems[index].id === id) {
  26535. return this.lensFlareSystems[index];
  26536. }
  26537. }
  26538. return null;
  26539. };
  26540. /**
  26541. * Gets a camera using its id
  26542. * @param id defines the id to look for
  26543. * @returns the camera or null if not found
  26544. */
  26545. Scene.prototype.getCameraByID = function (id) {
  26546. for (var index = 0; index < this.cameras.length; index++) {
  26547. if (this.cameras[index].id === id) {
  26548. return this.cameras[index];
  26549. }
  26550. }
  26551. return null;
  26552. };
  26553. /**
  26554. * Gets a camera using its unique id
  26555. * @param uniqueId defines the unique id to look for
  26556. * @returns the camera or null if not found
  26557. */
  26558. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26559. for (var index = 0; index < this.cameras.length; index++) {
  26560. if (this.cameras[index].uniqueId === uniqueId) {
  26561. return this.cameras[index];
  26562. }
  26563. }
  26564. return null;
  26565. };
  26566. /**
  26567. * Gets a camera using its name
  26568. * @param name defines the camera's name
  26569. * @return the camera or null if none found.
  26570. */
  26571. Scene.prototype.getCameraByName = function (name) {
  26572. for (var index = 0; index < this.cameras.length; index++) {
  26573. if (this.cameras[index].name === name) {
  26574. return this.cameras[index];
  26575. }
  26576. }
  26577. return null;
  26578. };
  26579. /**
  26580. * Gets a bone using its id
  26581. * @param id defines the bone's id
  26582. * @return the bone or null if not found
  26583. */
  26584. Scene.prototype.getBoneByID = function (id) {
  26585. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26586. var skeleton = this.skeletons[skeletonIndex];
  26587. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26588. if (skeleton.bones[boneIndex].id === id) {
  26589. return skeleton.bones[boneIndex];
  26590. }
  26591. }
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * Gets a bone using its id
  26597. * @param name defines the bone's name
  26598. * @return the bone or null if not found
  26599. */
  26600. Scene.prototype.getBoneByName = function (name) {
  26601. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26602. var skeleton = this.skeletons[skeletonIndex];
  26603. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26604. if (skeleton.bones[boneIndex].name === name) {
  26605. return skeleton.bones[boneIndex];
  26606. }
  26607. }
  26608. }
  26609. return null;
  26610. };
  26611. /**
  26612. * Gets a light node using its name
  26613. * @param name defines the the light's name
  26614. * @return the light or null if none found.
  26615. */
  26616. Scene.prototype.getLightByName = function (name) {
  26617. for (var index = 0; index < this.lights.length; index++) {
  26618. if (this.lights[index].name === name) {
  26619. return this.lights[index];
  26620. }
  26621. }
  26622. return null;
  26623. };
  26624. /**
  26625. * Gets a light node using its id
  26626. * @param id defines the light's id
  26627. * @return the light or null if none found.
  26628. */
  26629. Scene.prototype.getLightByID = function (id) {
  26630. for (var index = 0; index < this.lights.length; index++) {
  26631. if (this.lights[index].id === id) {
  26632. return this.lights[index];
  26633. }
  26634. }
  26635. return null;
  26636. };
  26637. /**
  26638. * Gets a light node using its scene-generated unique ID
  26639. * @param uniqueId defines the light's unique id
  26640. * @return the light or null if none found.
  26641. */
  26642. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26643. for (var index = 0; index < this.lights.length; index++) {
  26644. if (this.lights[index].uniqueId === uniqueId) {
  26645. return this.lights[index];
  26646. }
  26647. }
  26648. return null;
  26649. };
  26650. /**
  26651. * Gets a particle system by id
  26652. * @param id defines the particle system id
  26653. * @return the corresponding system or null if none found
  26654. */
  26655. Scene.prototype.getParticleSystemByID = function (id) {
  26656. for (var index = 0; index < this.particleSystems.length; index++) {
  26657. if (this.particleSystems[index].id === id) {
  26658. return this.particleSystems[index];
  26659. }
  26660. }
  26661. return null;
  26662. };
  26663. /**
  26664. * Gets a geometry using its ID
  26665. * @param id defines the geometry's id
  26666. * @return the geometry or null if none found.
  26667. */
  26668. Scene.prototype.getGeometryByID = function (id) {
  26669. for (var index = 0; index < this._geometries.length; index++) {
  26670. if (this._geometries[index].id === id) {
  26671. return this._geometries[index];
  26672. }
  26673. }
  26674. return null;
  26675. };
  26676. /**
  26677. * Add a new geometry to this scene
  26678. * @param geometry defines the geometry to be added to the scene.
  26679. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26680. * @return a boolean defining if the geometry was added or not
  26681. */
  26682. Scene.prototype.pushGeometry = function (geometry, force) {
  26683. if (!force && this.getGeometryByID(geometry.id)) {
  26684. return false;
  26685. }
  26686. this._geometries.push(geometry);
  26687. //notify the collision coordinator
  26688. if (this.collisionCoordinator) {
  26689. this.collisionCoordinator.onGeometryAdded(geometry);
  26690. }
  26691. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26692. return true;
  26693. };
  26694. /**
  26695. * Removes an existing geometry
  26696. * @param geometry defines the geometry to be removed from the scene
  26697. * @return a boolean defining if the geometry was removed or not
  26698. */
  26699. Scene.prototype.removeGeometry = function (geometry) {
  26700. var index = this._geometries.indexOf(geometry);
  26701. if (index > -1) {
  26702. this._geometries.splice(index, 1);
  26703. //notify the collision coordinator
  26704. if (this.collisionCoordinator) {
  26705. this.collisionCoordinator.onGeometryDeleted(geometry);
  26706. }
  26707. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26708. return true;
  26709. }
  26710. return false;
  26711. };
  26712. /**
  26713. * Gets the list of geometries attached to the scene
  26714. * @returns an array of Geometry
  26715. */
  26716. Scene.prototype.getGeometries = function () {
  26717. return this._geometries;
  26718. };
  26719. /**
  26720. * Gets the first added mesh found of a given ID
  26721. * @param id defines the id to search for
  26722. * @return the mesh found or null if not found at all
  26723. */
  26724. Scene.prototype.getMeshByID = function (id) {
  26725. for (var index = 0; index < this.meshes.length; index++) {
  26726. if (this.meshes[index].id === id) {
  26727. return this.meshes[index];
  26728. }
  26729. }
  26730. return null;
  26731. };
  26732. /**
  26733. * Gets a list of meshes using their id
  26734. * @param id defines the id to search for
  26735. * @returns a list of meshes
  26736. */
  26737. Scene.prototype.getMeshesByID = function (id) {
  26738. return this.meshes.filter(function (m) {
  26739. return m.id === id;
  26740. });
  26741. };
  26742. /**
  26743. * Gets the first added transform node found of a given ID
  26744. * @param id defines the id to search for
  26745. * @return the found transform node or null if not found at all.
  26746. */
  26747. Scene.prototype.getTransformNodeByID = function (id) {
  26748. for (var index = 0; index < this.transformNodes.length; index++) {
  26749. if (this.transformNodes[index].id === id) {
  26750. return this.transformNodes[index];
  26751. }
  26752. }
  26753. return null;
  26754. };
  26755. /**
  26756. * Gets a list of transform nodes using their id
  26757. * @param id defines the id to search for
  26758. * @returns a list of transform nodes
  26759. */
  26760. Scene.prototype.getTransformNodesByID = function (id) {
  26761. return this.transformNodes.filter(function (m) {
  26762. return m.id === id;
  26763. });
  26764. };
  26765. /**
  26766. * Gets a mesh with its auto-generated unique id
  26767. * @param uniqueId defines the unique id to search for
  26768. * @return the found mesh or null if not found at all.
  26769. */
  26770. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26771. for (var index = 0; index < this.meshes.length; index++) {
  26772. if (this.meshes[index].uniqueId === uniqueId) {
  26773. return this.meshes[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a the last added mesh using a given id
  26780. * @param id defines the id to search for
  26781. * @return the found mesh or null if not found at all.
  26782. */
  26783. Scene.prototype.getLastMeshByID = function (id) {
  26784. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26785. if (this.meshes[index].id === id) {
  26786. return this.meshes[index];
  26787. }
  26788. }
  26789. return null;
  26790. };
  26791. /**
  26792. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26793. * @param id defines the id to search for
  26794. * @return the found node or null if not found at all
  26795. */
  26796. Scene.prototype.getLastEntryByID = function (id) {
  26797. var index;
  26798. for (index = this.meshes.length - 1; index >= 0; index--) {
  26799. if (this.meshes[index].id === id) {
  26800. return this.meshes[index];
  26801. }
  26802. }
  26803. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26804. if (this.transformNodes[index].id === id) {
  26805. return this.transformNodes[index];
  26806. }
  26807. }
  26808. for (index = this.cameras.length - 1; index >= 0; index--) {
  26809. if (this.cameras[index].id === id) {
  26810. return this.cameras[index];
  26811. }
  26812. }
  26813. for (index = this.lights.length - 1; index >= 0; index--) {
  26814. if (this.lights[index].id === id) {
  26815. return this.lights[index];
  26816. }
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * Gets a node (Mesh, Camera, Light) using a given id
  26822. * @param id defines the id to search for
  26823. * @return the found node or null if not found at all
  26824. */
  26825. Scene.prototype.getNodeByID = function (id) {
  26826. var mesh = this.getMeshByID(id);
  26827. if (mesh) {
  26828. return mesh;
  26829. }
  26830. var light = this.getLightByID(id);
  26831. if (light) {
  26832. return light;
  26833. }
  26834. var camera = this.getCameraByID(id);
  26835. if (camera) {
  26836. return camera;
  26837. }
  26838. var bone = this.getBoneByID(id);
  26839. return bone;
  26840. };
  26841. /**
  26842. * Gets a node (Mesh, Camera, Light) using a given name
  26843. * @param name defines the name to search for
  26844. * @return the found node or null if not found at all.
  26845. */
  26846. Scene.prototype.getNodeByName = function (name) {
  26847. var mesh = this.getMeshByName(name);
  26848. if (mesh) {
  26849. return mesh;
  26850. }
  26851. var light = this.getLightByName(name);
  26852. if (light) {
  26853. return light;
  26854. }
  26855. var camera = this.getCameraByName(name);
  26856. if (camera) {
  26857. return camera;
  26858. }
  26859. var bone = this.getBoneByName(name);
  26860. return bone;
  26861. };
  26862. /**
  26863. * Gets a mesh using a given name
  26864. * @param name defines the name to search for
  26865. * @return the found mesh or null if not found at all.
  26866. */
  26867. Scene.prototype.getMeshByName = function (name) {
  26868. for (var index = 0; index < this.meshes.length; index++) {
  26869. if (this.meshes[index].name === name) {
  26870. return this.meshes[index];
  26871. }
  26872. }
  26873. return null;
  26874. };
  26875. /**
  26876. * Gets a transform node using a given name
  26877. * @param name defines the name to search for
  26878. * @return the found transform node or null if not found at all.
  26879. */
  26880. Scene.prototype.getTransformNodeByName = function (name) {
  26881. for (var index = 0; index < this.transformNodes.length; index++) {
  26882. if (this.transformNodes[index].name === name) {
  26883. return this.transformNodes[index];
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. /**
  26889. * Gets a sound using a given name
  26890. * @param name defines the name to search for
  26891. * @return the found sound or null if not found at all.
  26892. */
  26893. Scene.prototype.getSoundByName = function (name) {
  26894. var index;
  26895. if (BABYLON.AudioEngine) {
  26896. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26897. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26898. return this.mainSoundTrack.soundCollection[index];
  26899. }
  26900. }
  26901. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26902. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26903. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26904. return this.soundTracks[sdIndex].soundCollection[index];
  26905. }
  26906. }
  26907. }
  26908. }
  26909. return null;
  26910. };
  26911. /**
  26912. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26913. * @param id defines the id to search for
  26914. * @return the found skeleton or null if not found at all.
  26915. */
  26916. Scene.prototype.getLastSkeletonByID = function (id) {
  26917. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26918. if (this.skeletons[index].id === id) {
  26919. return this.skeletons[index];
  26920. }
  26921. }
  26922. return null;
  26923. };
  26924. /**
  26925. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26926. * @param id defines the id to search for
  26927. * @return the found skeleton or null if not found at all.
  26928. */
  26929. Scene.prototype.getSkeletonById = function (id) {
  26930. for (var index = 0; index < this.skeletons.length; index++) {
  26931. if (this.skeletons[index].id === id) {
  26932. return this.skeletons[index];
  26933. }
  26934. }
  26935. return null;
  26936. };
  26937. /**
  26938. * Gets a skeleton using a given name
  26939. * @param name defines the name to search for
  26940. * @return the found skeleton or null if not found at all.
  26941. */
  26942. Scene.prototype.getSkeletonByName = function (name) {
  26943. for (var index = 0; index < this.skeletons.length; index++) {
  26944. if (this.skeletons[index].name === name) {
  26945. return this.skeletons[index];
  26946. }
  26947. }
  26948. return null;
  26949. };
  26950. /**
  26951. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26952. * @param id defines the id to search for
  26953. * @return the found morph target manager or null if not found at all.
  26954. */
  26955. Scene.prototype.getMorphTargetManagerById = function (id) {
  26956. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26957. if (this.morphTargetManagers[index].uniqueId === id) {
  26958. return this.morphTargetManagers[index];
  26959. }
  26960. }
  26961. return null;
  26962. };
  26963. /**
  26964. * Gets a boolean indicating if the given mesh is active
  26965. * @param mesh defines the mesh to look for
  26966. * @returns true if the mesh is in the active list
  26967. */
  26968. Scene.prototype.isActiveMesh = function (mesh) {
  26969. return (this._activeMeshes.indexOf(mesh) !== -1);
  26970. };
  26971. /**
  26972. * Return a the first highlight layer of the scene with a given name.
  26973. * @param name The name of the highlight layer to look for.
  26974. * @return The highlight layer if found otherwise null.
  26975. */
  26976. Scene.prototype.getHighlightLayerByName = function (name) {
  26977. for (var index = 0; index < this.effectLayers.length; index++) {
  26978. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26979. return this.effectLayers[index];
  26980. }
  26981. }
  26982. return null;
  26983. };
  26984. /**
  26985. * Return a the first highlight layer of the scene with a given name.
  26986. * @param name The name of the highlight layer to look for.
  26987. * @return The highlight layer if found otherwise null.
  26988. */
  26989. Scene.prototype.getGlowLayerByName = function (name) {
  26990. for (var index = 0; index < this.effectLayers.length; index++) {
  26991. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26992. return this.effectLayers[index];
  26993. }
  26994. }
  26995. return null;
  26996. };
  26997. Object.defineProperty(Scene.prototype, "uid", {
  26998. /**
  26999. * Return a unique id as a string which can serve as an identifier for the scene
  27000. */
  27001. get: function () {
  27002. if (!this._uid) {
  27003. this._uid = BABYLON.Tools.RandomId();
  27004. }
  27005. return this._uid;
  27006. },
  27007. enumerable: true,
  27008. configurable: true
  27009. });
  27010. /**
  27011. * Add an externaly attached data from its key.
  27012. * This method call will fail and return false, if such key already exists.
  27013. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27014. * @param key the unique key that identifies the data
  27015. * @param data the data object to associate to the key for this Engine instance
  27016. * @return true if no such key were already present and the data was added successfully, false otherwise
  27017. */
  27018. Scene.prototype.addExternalData = function (key, data) {
  27019. if (!this._externalData) {
  27020. this._externalData = new BABYLON.StringDictionary();
  27021. }
  27022. return this._externalData.add(key, data);
  27023. };
  27024. /**
  27025. * Get an externaly attached data from its key
  27026. * @param key the unique key that identifies the data
  27027. * @return the associated data, if present (can be null), or undefined if not present
  27028. */
  27029. Scene.prototype.getExternalData = function (key) {
  27030. if (!this._externalData) {
  27031. return null;
  27032. }
  27033. return this._externalData.get(key);
  27034. };
  27035. /**
  27036. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27037. * @param key the unique key that identifies the data
  27038. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27039. * @return the associated data, can be null if the factory returned null.
  27040. */
  27041. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27042. if (!this._externalData) {
  27043. this._externalData = new BABYLON.StringDictionary();
  27044. }
  27045. return this._externalData.getOrAddWithFactory(key, factory);
  27046. };
  27047. /**
  27048. * Remove an externaly attached data from the Engine instance
  27049. * @param key the unique key that identifies the data
  27050. * @return true if the data was successfully removed, false if it doesn't exist
  27051. */
  27052. Scene.prototype.removeExternalData = function (key) {
  27053. return this._externalData.remove(key);
  27054. };
  27055. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27056. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27057. if (mesh.showSubMeshesBoundingBox) {
  27058. var boundingInfo = subMesh.getBoundingInfo();
  27059. if (boundingInfo !== null && boundingInfo !== undefined) {
  27060. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27061. }
  27062. }
  27063. var material = subMesh.getMaterial();
  27064. if (material !== null && material !== undefined) {
  27065. // Render targets
  27066. if (material.getRenderTargetTextures !== undefined) {
  27067. if (this._processedMaterials.indexOf(material) === -1) {
  27068. this._processedMaterials.push(material);
  27069. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27070. }
  27071. }
  27072. // Dispatch
  27073. this._activeIndices.addCount(subMesh.indexCount, false);
  27074. this._renderingManager.dispatch(subMesh, mesh, material);
  27075. }
  27076. }
  27077. };
  27078. /**
  27079. * Clear the processed materials smart array preventing retention point in material dispose.
  27080. */
  27081. Scene.prototype.freeProcessedMaterials = function () {
  27082. this._processedMaterials.dispose();
  27083. };
  27084. /**
  27085. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27086. */
  27087. Scene.prototype.freeActiveMeshes = function () {
  27088. this._activeMeshes.dispose();
  27089. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27090. this.activeCamera._activeMeshes.dispose();
  27091. }
  27092. if (this.activeCameras) {
  27093. for (var i = 0; i < this.activeCameras.length; i++) {
  27094. var activeCamera = this.activeCameras[i];
  27095. if (activeCamera && activeCamera._activeMeshes) {
  27096. activeCamera._activeMeshes.dispose();
  27097. }
  27098. }
  27099. }
  27100. };
  27101. /**
  27102. * Clear the info related to rendering groups preventing retention points during dispose.
  27103. */
  27104. Scene.prototype.freeRenderingGroups = function () {
  27105. if (this._renderingManager) {
  27106. this._renderingManager.freeRenderingGroups();
  27107. }
  27108. if (this.textures) {
  27109. for (var i = 0; i < this.textures.length; i++) {
  27110. var texture = this.textures[i];
  27111. if (texture && texture.renderList) {
  27112. texture.freeRenderingGroups();
  27113. }
  27114. }
  27115. }
  27116. };
  27117. /** @hidden */
  27118. Scene.prototype._isInIntermediateRendering = function () {
  27119. return this._intermediateRendering;
  27120. };
  27121. /**
  27122. * Defines the current active mesh candidate provider
  27123. * @param provider defines the provider to use
  27124. */
  27125. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27126. this._activeMeshCandidateProvider = provider;
  27127. };
  27128. /**
  27129. * Gets the current active mesh candidate provider
  27130. * @returns the current active mesh candidate provider
  27131. */
  27132. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27133. return this._activeMeshCandidateProvider;
  27134. };
  27135. /**
  27136. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27137. * @returns the current scene
  27138. */
  27139. Scene.prototype.freezeActiveMeshes = function () {
  27140. if (!this.activeCamera) {
  27141. return this;
  27142. }
  27143. if (!this._frustumPlanes) {
  27144. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27145. }
  27146. this._evaluateActiveMeshes();
  27147. this._activeMeshesFrozen = true;
  27148. return this;
  27149. };
  27150. /**
  27151. * Use this function to restart evaluating active meshes on every frame
  27152. * @returns the current scene
  27153. */
  27154. Scene.prototype.unfreezeActiveMeshes = function () {
  27155. this._activeMeshesFrozen = false;
  27156. return this;
  27157. };
  27158. Scene.prototype._evaluateActiveMeshes = function () {
  27159. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27160. return;
  27161. }
  27162. if (!this.activeCamera) {
  27163. return;
  27164. }
  27165. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27166. this.activeCamera._activeMeshes.reset();
  27167. this._activeMeshes.reset();
  27168. this._renderingManager.reset();
  27169. this._processedMaterials.reset();
  27170. this._activeParticleSystems.reset();
  27171. this._activeSkeletons.reset();
  27172. this._softwareSkinnedMeshes.reset();
  27173. if (this._boundingBoxRenderer) {
  27174. this._boundingBoxRenderer.reset();
  27175. }
  27176. // Meshes
  27177. var meshes;
  27178. var len;
  27179. var checkIsEnabled = true;
  27180. // Determine mesh candidates
  27181. if (this._activeMeshCandidateProvider !== undefined) {
  27182. // Use _activeMeshCandidateProvider
  27183. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27184. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27185. if (meshes !== undefined) {
  27186. len = meshes.length;
  27187. }
  27188. else {
  27189. len = 0;
  27190. }
  27191. }
  27192. else if (this._selectionOctree !== undefined) {
  27193. // Octree
  27194. var selection = this._selectionOctree.select(this._frustumPlanes);
  27195. meshes = selection.data;
  27196. len = selection.length;
  27197. }
  27198. else {
  27199. // Full scene traversal
  27200. len = this.meshes.length;
  27201. meshes = this.meshes;
  27202. }
  27203. // Check each mesh
  27204. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27205. mesh = meshes[meshIndex];
  27206. if (mesh.isBlocked) {
  27207. continue;
  27208. }
  27209. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27210. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27211. continue;
  27212. }
  27213. mesh.computeWorldMatrix();
  27214. // Intersections
  27215. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27216. this._meshesForIntersections.pushNoDuplicate(mesh);
  27217. }
  27218. // Switch to current LOD
  27219. meshLOD = mesh.getLOD(this.activeCamera);
  27220. if (meshLOD === undefined || meshLOD === null) {
  27221. continue;
  27222. }
  27223. mesh._preActivate();
  27224. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27225. this._activeMeshes.push(mesh);
  27226. this.activeCamera._activeMeshes.push(mesh);
  27227. mesh._activate(this._renderId);
  27228. if (meshLOD !== mesh) {
  27229. meshLOD._activate(this._renderId);
  27230. }
  27231. this._activeMesh(mesh, meshLOD);
  27232. }
  27233. }
  27234. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27235. // Particle systems
  27236. if (this.particlesEnabled) {
  27237. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27238. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27239. var particleSystem = this.particleSystems[particleIndex];
  27240. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27241. continue;
  27242. }
  27243. var emitter = particleSystem.emitter;
  27244. if (!emitter.position || emitter.isEnabled()) {
  27245. this._activeParticleSystems.push(particleSystem);
  27246. particleSystem.animate();
  27247. this._renderingManager.dispatchParticles(particleSystem);
  27248. }
  27249. }
  27250. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27251. }
  27252. };
  27253. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27254. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27255. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27256. mesh.skeleton.prepare();
  27257. }
  27258. if (!mesh.computeBonesUsingShaders) {
  27259. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27260. }
  27261. }
  27262. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27263. var boundingInfo = sourceMesh.getBoundingInfo();
  27264. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27265. }
  27266. if (mesh !== undefined && mesh !== null
  27267. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27268. // Submeshes Octrees
  27269. var len;
  27270. var subMeshes;
  27271. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27272. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27273. len = intersections.length;
  27274. subMeshes = intersections.data;
  27275. }
  27276. else {
  27277. subMeshes = mesh.subMeshes;
  27278. len = subMeshes.length;
  27279. }
  27280. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27281. subMesh = subMeshes[subIndex];
  27282. this._evaluateSubMesh(subMesh, mesh);
  27283. }
  27284. }
  27285. };
  27286. /**
  27287. * Update the transform matrix to update from the current active camera
  27288. * @param force defines a boolean used to force the update even if cache is up to date
  27289. */
  27290. Scene.prototype.updateTransformMatrix = function (force) {
  27291. if (!this.activeCamera) {
  27292. return;
  27293. }
  27294. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27295. };
  27296. /**
  27297. * 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)
  27298. * @param alternateCamera defines the camera to use
  27299. */
  27300. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27301. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27302. };
  27303. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27304. if (camera && camera._skipRendering) {
  27305. return;
  27306. }
  27307. var engine = this._engine;
  27308. this.activeCamera = camera;
  27309. if (!this.activeCamera)
  27310. throw new Error("Active camera not set");
  27311. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27312. // Viewport
  27313. engine.setViewport(this.activeCamera.viewport);
  27314. // Camera
  27315. this.resetCachedMaterial();
  27316. this._renderId++;
  27317. this.updateTransformMatrix();
  27318. if (camera._alternateCamera) {
  27319. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27320. this._alternateRendering = true;
  27321. }
  27322. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27323. // Meshes
  27324. this._evaluateActiveMeshes();
  27325. // Software skinning
  27326. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27327. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27328. mesh.applySkeleton(mesh.skeleton);
  27329. }
  27330. // Render targets
  27331. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27332. var needsRestoreFrameBuffer = false;
  27333. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27334. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27335. }
  27336. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27337. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27338. }
  27339. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27340. this._intermediateRendering = true;
  27341. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27342. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27343. var renderTarget = this._renderTargets.data[renderIndex];
  27344. if (renderTarget._shouldRender()) {
  27345. this._renderId++;
  27346. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27347. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27348. }
  27349. }
  27350. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27351. this._intermediateRendering = false;
  27352. this._renderId++;
  27353. needsRestoreFrameBuffer = true; // Restore back buffer
  27354. }
  27355. // Render EffecttLayer Texture
  27356. var stencilState = this._engine.getStencilBuffer();
  27357. var renderEffects = false;
  27358. var needStencil = false;
  27359. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27360. this._intermediateRendering = true;
  27361. for (var i = 0; i < this.effectLayers.length; i++) {
  27362. var effectLayer = this.effectLayers[i];
  27363. if (effectLayer.shouldRender() &&
  27364. (!effectLayer.camera ||
  27365. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27366. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27367. renderEffects = true;
  27368. needStencil = needStencil || effectLayer.needStencil();
  27369. var renderTarget = effectLayer._mainTexture;
  27370. if (renderTarget._shouldRender()) {
  27371. this._renderId++;
  27372. renderTarget.render(false, false);
  27373. needsRestoreFrameBuffer = true;
  27374. }
  27375. }
  27376. }
  27377. this._intermediateRendering = false;
  27378. this._renderId++;
  27379. }
  27380. if (needsRestoreFrameBuffer) {
  27381. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27382. }
  27383. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27384. // Prepare Frame
  27385. this.postProcessManager._prepareFrame();
  27386. // Backgrounds
  27387. var layerIndex;
  27388. var layer;
  27389. if (this.layers.length) {
  27390. engine.setDepthBuffer(false);
  27391. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27392. layer = this.layers[layerIndex];
  27393. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27394. layer.render();
  27395. }
  27396. }
  27397. engine.setDepthBuffer(true);
  27398. }
  27399. // Activate effect Layer stencil
  27400. if (needStencil) {
  27401. this._engine.setStencilBuffer(true);
  27402. }
  27403. // Render
  27404. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27405. this._renderingManager.render(null, null, true, true);
  27406. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27407. // Restore effect Layer stencil
  27408. if (needStencil) {
  27409. this._engine.setStencilBuffer(stencilState);
  27410. }
  27411. // Bounding boxes
  27412. if (this._boundingBoxRenderer) {
  27413. this._boundingBoxRenderer.render();
  27414. }
  27415. // Lens flares
  27416. if (this.lensFlaresEnabled) {
  27417. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27418. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27419. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27420. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27421. lensFlareSystem.render();
  27422. }
  27423. }
  27424. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27425. }
  27426. // Effect Layer
  27427. if (renderEffects) {
  27428. engine.setDepthBuffer(false);
  27429. for (var i = 0; i < this.effectLayers.length; i++) {
  27430. if (this.effectLayers[i].shouldRender()) {
  27431. this.effectLayers[i].render();
  27432. }
  27433. }
  27434. engine.setDepthBuffer(true);
  27435. }
  27436. // Foregrounds
  27437. if (this.layers.length) {
  27438. engine.setDepthBuffer(false);
  27439. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27440. layer = this.layers[layerIndex];
  27441. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27442. layer.render();
  27443. }
  27444. }
  27445. engine.setDepthBuffer(true);
  27446. }
  27447. // Finalize frame
  27448. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27449. // Reset some special arrays
  27450. this._renderTargets.reset();
  27451. this._alternateRendering = false;
  27452. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27453. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27454. };
  27455. Scene.prototype._processSubCameras = function (camera) {
  27456. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27457. this._renderForCamera(camera);
  27458. return;
  27459. }
  27460. // rig cameras
  27461. for (var index = 0; index < camera._rigCameras.length; index++) {
  27462. this._renderForCamera(camera._rigCameras[index], camera);
  27463. }
  27464. this.activeCamera = camera;
  27465. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27466. };
  27467. Scene.prototype._checkIntersections = function () {
  27468. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27469. var sourceMesh = this._meshesForIntersections.data[index];
  27470. if (!sourceMesh.actionManager) {
  27471. continue;
  27472. }
  27473. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27474. var action = sourceMesh.actionManager.actions[actionIndex];
  27475. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27476. var parameters = action.getTriggerParameter();
  27477. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27478. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27479. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27480. if (areIntersecting && currentIntersectionInProgress === -1) {
  27481. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27482. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27483. sourceMesh._intersectionsInProgress.push(otherMesh);
  27484. }
  27485. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27486. sourceMesh._intersectionsInProgress.push(otherMesh);
  27487. }
  27488. }
  27489. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27490. //They intersected, and now they don't.
  27491. //is this trigger an exit trigger? execute an event.
  27492. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27493. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27494. }
  27495. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27496. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27497. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27498. return otherMesh === parameterMesh;
  27499. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27500. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27501. }
  27502. }
  27503. }
  27504. }
  27505. }
  27506. };
  27507. /**
  27508. * Render the scene
  27509. */
  27510. Scene.prototype.render = function () {
  27511. if (this.isDisposed) {
  27512. return;
  27513. }
  27514. this._activeParticles.fetchNewFrame();
  27515. this._totalVertices.fetchNewFrame();
  27516. this._activeIndices.fetchNewFrame();
  27517. this._activeBones.fetchNewFrame();
  27518. this._meshesForIntersections.reset();
  27519. this.resetCachedMaterial();
  27520. this.onBeforeAnimationsObservable.notifyObservers(this);
  27521. // Actions
  27522. if (this.actionManager) {
  27523. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27524. }
  27525. //Simplification Queue
  27526. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27527. this.simplificationQueue.executeNext();
  27528. }
  27529. if (this._engine.isDeterministicLockStep()) {
  27530. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27531. var defaultFPS = (60.0 / 1000.0);
  27532. var defaultFrameTime = 1000 / 60; // frame time in MS
  27533. if (this._physicsEngine) {
  27534. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27535. }
  27536. var stepsTaken = 0;
  27537. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27538. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27539. internalSteps = Math.min(internalSteps, maxSubSteps);
  27540. do {
  27541. this.onBeforeStepObservable.notifyObservers(this);
  27542. // Animations
  27543. this._animationRatio = defaultFrameTime * defaultFPS;
  27544. this._animate();
  27545. this.onAfterAnimationsObservable.notifyObservers(this);
  27546. // Physics
  27547. if (this._physicsEngine) {
  27548. this.onBeforePhysicsObservable.notifyObservers(this);
  27549. this._physicsEngine._step(defaultFrameTime / 1000);
  27550. this.onAfterPhysicsObservable.notifyObservers(this);
  27551. }
  27552. this.onAfterStepObservable.notifyObservers(this);
  27553. this._currentStepId++;
  27554. stepsTaken++;
  27555. deltaTime -= defaultFrameTime;
  27556. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27557. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27558. }
  27559. else {
  27560. // Animations
  27561. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27562. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27563. this._animate();
  27564. this.onAfterAnimationsObservable.notifyObservers(this);
  27565. // Physics
  27566. if (this._physicsEngine) {
  27567. this.onBeforePhysicsObservable.notifyObservers(this);
  27568. this._physicsEngine._step(deltaTime / 1000.0);
  27569. this.onAfterPhysicsObservable.notifyObservers(this);
  27570. }
  27571. }
  27572. // update gamepad manager
  27573. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27574. this._gamepadManager._checkGamepadsStatus();
  27575. }
  27576. // Update Cameras
  27577. if (this.activeCameras.length > 0) {
  27578. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27579. var camera = this.activeCameras[cameraIndex];
  27580. camera.update();
  27581. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27582. // rig cameras
  27583. for (var index = 0; index < camera._rigCameras.length; index++) {
  27584. camera._rigCameras[index].update();
  27585. }
  27586. }
  27587. }
  27588. }
  27589. else if (this.activeCamera) {
  27590. this.activeCamera.update();
  27591. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27592. // rig cameras
  27593. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27594. this.activeCamera._rigCameras[index].update();
  27595. }
  27596. }
  27597. }
  27598. // Before render
  27599. this.onBeforeRenderObservable.notifyObservers(this);
  27600. // Customs render targets
  27601. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27602. var engine = this.getEngine();
  27603. var currentActiveCamera = this.activeCamera;
  27604. if (this.renderTargetsEnabled) {
  27605. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27606. this._intermediateRendering = true;
  27607. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27608. var renderTarget = this.customRenderTargets[customIndex];
  27609. if (renderTarget._shouldRender()) {
  27610. this._renderId++;
  27611. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27612. if (!this.activeCamera)
  27613. throw new Error("Active camera not set");
  27614. // Viewport
  27615. engine.setViewport(this.activeCamera.viewport);
  27616. // Camera
  27617. this.updateTransformMatrix();
  27618. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27619. }
  27620. }
  27621. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27622. this._intermediateRendering = false;
  27623. this._renderId++;
  27624. }
  27625. // Restore back buffer
  27626. if (this.customRenderTargets.length > 0) {
  27627. engine.restoreDefaultFramebuffer();
  27628. }
  27629. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27630. this.activeCamera = currentActiveCamera;
  27631. // Procedural textures
  27632. if (this.proceduralTexturesEnabled) {
  27633. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27634. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27635. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27636. if (proceduralTexture._shouldRender()) {
  27637. proceduralTexture.render();
  27638. }
  27639. }
  27640. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27641. }
  27642. // Clear
  27643. if (this.autoClearDepthAndStencil || this.autoClear) {
  27644. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27645. }
  27646. // Shadows
  27647. if (this.shadowsEnabled) {
  27648. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27649. var light = this.lights[lightIndex];
  27650. var shadowGenerator = light.getShadowGenerator();
  27651. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27652. var shadowMap = (shadowGenerator.getShadowMap());
  27653. if (this.textures.indexOf(shadowMap) !== -1) {
  27654. this._renderTargets.push(shadowMap);
  27655. }
  27656. }
  27657. }
  27658. }
  27659. // Depth renderer
  27660. for (var key in this._depthRenderer) {
  27661. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27662. }
  27663. // Geometry renderer
  27664. if (this._geometryBufferRenderer) {
  27665. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27666. }
  27667. // RenderPipeline
  27668. if (this._postProcessRenderPipelineManager) {
  27669. this._postProcessRenderPipelineManager.update();
  27670. }
  27671. // Multi-cameras?
  27672. if (this.activeCameras.length > 0) {
  27673. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27674. if (cameraIndex > 0) {
  27675. this._engine.clear(null, false, true, true);
  27676. }
  27677. this._processSubCameras(this.activeCameras[cameraIndex]);
  27678. }
  27679. }
  27680. else {
  27681. if (!this.activeCamera) {
  27682. throw new Error("No camera defined");
  27683. }
  27684. this._processSubCameras(this.activeCamera);
  27685. }
  27686. // Intersection checks
  27687. this._checkIntersections();
  27688. // Update the audio listener attached to the camera
  27689. if (BABYLON.AudioEngine) {
  27690. this._updateAudioParameters();
  27691. }
  27692. // After render
  27693. if (this.afterRender) {
  27694. this.afterRender();
  27695. }
  27696. this.onAfterRenderObservable.notifyObservers(this);
  27697. // Cleaning
  27698. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27699. var data = this._toBeDisposed.data[index];
  27700. if (data) {
  27701. data.dispose();
  27702. }
  27703. this._toBeDisposed[index] = null;
  27704. }
  27705. this._toBeDisposed.reset();
  27706. if (this.dumpNextRenderTargets) {
  27707. this.dumpNextRenderTargets = false;
  27708. }
  27709. this._activeBones.addCount(0, true);
  27710. this._activeIndices.addCount(0, true);
  27711. this._activeParticles.addCount(0, true);
  27712. };
  27713. Scene.prototype._updateAudioParameters = function () {
  27714. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27715. return;
  27716. }
  27717. var listeningCamera;
  27718. var audioEngine = BABYLON.Engine.audioEngine;
  27719. if (this.activeCameras.length > 0) {
  27720. listeningCamera = this.activeCameras[0];
  27721. }
  27722. else {
  27723. listeningCamera = this.activeCamera;
  27724. }
  27725. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27726. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27727. // for VR cameras
  27728. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27729. listeningCamera = listeningCamera.rigCameras[0];
  27730. }
  27731. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27732. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27733. cameraDirection.normalize();
  27734. // To avoid some errors on GearVR
  27735. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27736. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27737. }
  27738. var i;
  27739. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27740. var sound = this.mainSoundTrack.soundCollection[i];
  27741. if (sound.useCustomAttenuation) {
  27742. sound.updateDistanceFromListener();
  27743. }
  27744. }
  27745. for (i = 0; i < this.soundTracks.length; i++) {
  27746. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27747. sound = this.soundTracks[i].soundCollection[j];
  27748. if (sound.useCustomAttenuation) {
  27749. sound.updateDistanceFromListener();
  27750. }
  27751. }
  27752. }
  27753. }
  27754. };
  27755. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27756. // Audio
  27757. /**
  27758. * Gets or sets if audio support is enabled
  27759. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27760. */
  27761. get: function () {
  27762. return this._audioEnabled;
  27763. },
  27764. set: function (value) {
  27765. this._audioEnabled = value;
  27766. if (BABYLON.AudioEngine) {
  27767. if (this._audioEnabled) {
  27768. this._enableAudio();
  27769. }
  27770. else {
  27771. this._disableAudio();
  27772. }
  27773. }
  27774. },
  27775. enumerable: true,
  27776. configurable: true
  27777. });
  27778. Scene.prototype._disableAudio = function () {
  27779. var i;
  27780. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27781. this.mainSoundTrack.soundCollection[i].pause();
  27782. }
  27783. for (i = 0; i < this.soundTracks.length; i++) {
  27784. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27785. this.soundTracks[i].soundCollection[j].pause();
  27786. }
  27787. }
  27788. };
  27789. Scene.prototype._enableAudio = function () {
  27790. var i;
  27791. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27792. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27793. this.mainSoundTrack.soundCollection[i].play();
  27794. }
  27795. }
  27796. for (i = 0; i < this.soundTracks.length; i++) {
  27797. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27798. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27799. this.soundTracks[i].soundCollection[j].play();
  27800. }
  27801. }
  27802. }
  27803. };
  27804. Object.defineProperty(Scene.prototype, "headphone", {
  27805. /**
  27806. * Gets or sets if audio will be output to headphones
  27807. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27808. */
  27809. get: function () {
  27810. return this._headphone;
  27811. },
  27812. set: function (value) {
  27813. this._headphone = value;
  27814. if (BABYLON.AudioEngine) {
  27815. if (this._headphone) {
  27816. this._switchAudioModeForHeadphones();
  27817. }
  27818. else {
  27819. this._switchAudioModeForNormalSpeakers();
  27820. }
  27821. }
  27822. },
  27823. enumerable: true,
  27824. configurable: true
  27825. });
  27826. Scene.prototype._switchAudioModeForHeadphones = function () {
  27827. this.mainSoundTrack.switchPanningModelToHRTF();
  27828. for (var i = 0; i < this.soundTracks.length; i++) {
  27829. this.soundTracks[i].switchPanningModelToHRTF();
  27830. }
  27831. };
  27832. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27833. this.mainSoundTrack.switchPanningModelToEqualPower();
  27834. for (var i = 0; i < this.soundTracks.length; i++) {
  27835. this.soundTracks[i].switchPanningModelToEqualPower();
  27836. }
  27837. };
  27838. /**
  27839. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27840. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27841. * @returns the created depth renderer
  27842. */
  27843. Scene.prototype.enableDepthRenderer = function (camera) {
  27844. camera = camera || this.activeCamera;
  27845. if (!camera) {
  27846. throw "No camera available to enable depth renderer";
  27847. }
  27848. if (!this._depthRenderer[camera.id]) {
  27849. var textureType = 0;
  27850. if (this._engine.getCaps().textureHalfFloatRender) {
  27851. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27852. }
  27853. else if (this._engine.getCaps().textureFloatRender) {
  27854. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27855. }
  27856. else {
  27857. throw "Depth renderer does not support int texture type";
  27858. }
  27859. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27860. }
  27861. return this._depthRenderer[camera.id];
  27862. };
  27863. /**
  27864. * Disables a depth renderer for a given camera
  27865. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27866. */
  27867. Scene.prototype.disableDepthRenderer = function (camera) {
  27868. camera = camera || this.activeCamera;
  27869. if (!camera || !this._depthRenderer[camera.id]) {
  27870. return;
  27871. }
  27872. this._depthRenderer[camera.id].dispose();
  27873. delete this._depthRenderer[camera.id];
  27874. };
  27875. /**
  27876. * Enables a GeometryBufferRender and associates it with the scene
  27877. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27878. * @returns the GeometryBufferRenderer
  27879. */
  27880. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27881. if (ratio === void 0) { ratio = 1; }
  27882. if (this._geometryBufferRenderer) {
  27883. return this._geometryBufferRenderer;
  27884. }
  27885. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27886. if (!this._geometryBufferRenderer.isSupported) {
  27887. this._geometryBufferRenderer = null;
  27888. }
  27889. return this._geometryBufferRenderer;
  27890. };
  27891. /**
  27892. * Disables the GeometryBufferRender associated with the scene
  27893. */
  27894. Scene.prototype.disableGeometryBufferRenderer = function () {
  27895. if (!this._geometryBufferRenderer) {
  27896. return;
  27897. }
  27898. this._geometryBufferRenderer.dispose();
  27899. this._geometryBufferRenderer = null;
  27900. };
  27901. /**
  27902. * Freeze all materials
  27903. * A frozen material will not be updatable but should be faster to render
  27904. */
  27905. Scene.prototype.freezeMaterials = function () {
  27906. for (var i = 0; i < this.materials.length; i++) {
  27907. this.materials[i].freeze();
  27908. }
  27909. };
  27910. /**
  27911. * Unfreeze all materials
  27912. * A frozen material will not be updatable but should be faster to render
  27913. */
  27914. Scene.prototype.unfreezeMaterials = function () {
  27915. for (var i = 0; i < this.materials.length; i++) {
  27916. this.materials[i].unfreeze();
  27917. }
  27918. };
  27919. /**
  27920. * Releases all held ressources
  27921. */
  27922. Scene.prototype.dispose = function () {
  27923. this.beforeRender = null;
  27924. this.afterRender = null;
  27925. this.skeletons = [];
  27926. this.morphTargetManagers = [];
  27927. this.importedMeshesFiles = new Array();
  27928. this.stopAllAnimations();
  27929. this.resetCachedMaterial();
  27930. for (var key in this._depthRenderer) {
  27931. this._depthRenderer[key].dispose();
  27932. }
  27933. if (this._gamepadManager) {
  27934. this._gamepadManager.dispose();
  27935. this._gamepadManager = null;
  27936. }
  27937. // Smart arrays
  27938. if (this.activeCamera) {
  27939. this.activeCamera._activeMeshes.dispose();
  27940. this.activeCamera = null;
  27941. }
  27942. this._activeMeshes.dispose();
  27943. this._renderingManager.dispose();
  27944. this._processedMaterials.dispose();
  27945. this._activeParticleSystems.dispose();
  27946. this._activeSkeletons.dispose();
  27947. this._softwareSkinnedMeshes.dispose();
  27948. this._renderTargets.dispose();
  27949. this._registeredForLateAnimationBindings.dispose();
  27950. if (this._boundingBoxRenderer) {
  27951. this._boundingBoxRenderer.dispose();
  27952. }
  27953. this._meshesForIntersections.dispose();
  27954. this._toBeDisposed.dispose();
  27955. // Abort active requests
  27956. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27957. var request = _a[_i];
  27958. request.abort();
  27959. }
  27960. // Debug layer
  27961. if (this._debugLayer) {
  27962. this._debugLayer.hide();
  27963. }
  27964. // Events
  27965. this.onDisposeObservable.notifyObservers(this);
  27966. this.onDisposeObservable.clear();
  27967. this.onBeforeRenderObservable.clear();
  27968. this.onAfterRenderObservable.clear();
  27969. this.onBeforeRenderTargetsRenderObservable.clear();
  27970. this.onAfterRenderTargetsRenderObservable.clear();
  27971. this.onAfterStepObservable.clear();
  27972. this.onBeforeStepObservable.clear();
  27973. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27974. this.onAfterActiveMeshesEvaluationObservable.clear();
  27975. this.onBeforeParticlesRenderingObservable.clear();
  27976. this.onAfterParticlesRenderingObservable.clear();
  27977. this.onBeforeSpritesRenderingObservable.clear();
  27978. this.onAfterSpritesRenderingObservable.clear();
  27979. this.onBeforeDrawPhaseObservable.clear();
  27980. this.onAfterDrawPhaseObservable.clear();
  27981. this.onBeforePhysicsObservable.clear();
  27982. this.onAfterPhysicsObservable.clear();
  27983. this.onBeforeAnimationsObservable.clear();
  27984. this.onAfterAnimationsObservable.clear();
  27985. this.onDataLoadedObservable.clear();
  27986. this.detachControl();
  27987. // Release sounds & sounds tracks
  27988. if (BABYLON.AudioEngine) {
  27989. this.disposeSounds();
  27990. }
  27991. // VR Helper
  27992. if (this.VRHelper) {
  27993. this.VRHelper.dispose();
  27994. }
  27995. // Detach cameras
  27996. var canvas = this._engine.getRenderingCanvas();
  27997. if (canvas) {
  27998. var index;
  27999. for (index = 0; index < this.cameras.length; index++) {
  28000. this.cameras[index].detachControl(canvas);
  28001. }
  28002. }
  28003. // Release animation groups
  28004. while (this.animationGroups.length) {
  28005. this.animationGroups[0].dispose();
  28006. }
  28007. // Release lights
  28008. while (this.lights.length) {
  28009. this.lights[0].dispose();
  28010. }
  28011. // Release meshes
  28012. while (this.meshes.length) {
  28013. this.meshes[0].dispose(true);
  28014. }
  28015. while (this.transformNodes.length) {
  28016. this.removeTransformNode(this.transformNodes[0]);
  28017. }
  28018. // Release cameras
  28019. while (this.cameras.length) {
  28020. this.cameras[0].dispose();
  28021. }
  28022. // Release materials
  28023. if (this.defaultMaterial) {
  28024. this.defaultMaterial.dispose();
  28025. }
  28026. while (this.multiMaterials.length) {
  28027. this.multiMaterials[0].dispose();
  28028. }
  28029. while (this.materials.length) {
  28030. this.materials[0].dispose();
  28031. }
  28032. // Release particles
  28033. while (this.particleSystems.length) {
  28034. this.particleSystems[0].dispose();
  28035. }
  28036. // Release sprites
  28037. while (this.spriteManagers.length) {
  28038. this.spriteManagers[0].dispose();
  28039. }
  28040. // Release postProcesses
  28041. while (this.postProcesses.length) {
  28042. this.postProcesses[0].dispose();
  28043. }
  28044. // Release layers
  28045. while (this.layers.length) {
  28046. this.layers[0].dispose();
  28047. }
  28048. while (this.effectLayers.length) {
  28049. this.effectLayers[0].dispose();
  28050. }
  28051. // Release textures
  28052. while (this.textures.length) {
  28053. this.textures[0].dispose();
  28054. }
  28055. // Release UBO
  28056. this._sceneUbo.dispose();
  28057. if (this._alternateSceneUbo) {
  28058. this._alternateSceneUbo.dispose();
  28059. }
  28060. // Post-processes
  28061. this.postProcessManager.dispose();
  28062. if (this._postProcessRenderPipelineManager) {
  28063. this._postProcessRenderPipelineManager.dispose();
  28064. }
  28065. // Physics
  28066. if (this._physicsEngine) {
  28067. this.disablePhysicsEngine();
  28068. }
  28069. // Remove from engine
  28070. index = this._engine.scenes.indexOf(this);
  28071. if (index > -1) {
  28072. this._engine.scenes.splice(index, 1);
  28073. }
  28074. this._engine.wipeCaches(true);
  28075. this._isDisposed = true;
  28076. };
  28077. Object.defineProperty(Scene.prototype, "isDisposed", {
  28078. /**
  28079. * Gets if the scene is already disposed
  28080. */
  28081. get: function () {
  28082. return this._isDisposed;
  28083. },
  28084. enumerable: true,
  28085. configurable: true
  28086. });
  28087. /**
  28088. * Releases sounds & soundtracks
  28089. */
  28090. Scene.prototype.disposeSounds = function () {
  28091. if (!this._mainSoundTrack) {
  28092. return;
  28093. }
  28094. this.mainSoundTrack.dispose();
  28095. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28096. this.soundTracks[scIndex].dispose();
  28097. }
  28098. };
  28099. // Octrees
  28100. /**
  28101. * Get the world extend vectors with an optional filter
  28102. *
  28103. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28104. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28105. */
  28106. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28107. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28108. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28109. filterPredicate = filterPredicate || (function () { return true; });
  28110. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28111. mesh.computeWorldMatrix(true);
  28112. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28113. return;
  28114. }
  28115. var boundingInfo = mesh.getBoundingInfo();
  28116. var minBox = boundingInfo.boundingBox.minimumWorld;
  28117. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28118. BABYLON.Tools.CheckExtends(minBox, min, max);
  28119. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28120. });
  28121. return {
  28122. min: min,
  28123. max: max
  28124. };
  28125. };
  28126. /**
  28127. * Creates or updates the octree used to boost selection (picking)
  28128. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28129. * @param maxCapacity defines the maximum capacity per leaf
  28130. * @param maxDepth defines the maximum depth of the octree
  28131. * @returns an octree of AbstractMesh
  28132. */
  28133. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28134. if (maxCapacity === void 0) { maxCapacity = 64; }
  28135. if (maxDepth === void 0) { maxDepth = 2; }
  28136. if (!this._selectionOctree) {
  28137. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28138. }
  28139. var worldExtends = this.getWorldExtends();
  28140. // Update octree
  28141. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28142. return this._selectionOctree;
  28143. };
  28144. // Picking
  28145. /**
  28146. * Creates a ray that can be used to pick in the scene
  28147. * @param x defines the x coordinate of the origin (on-screen)
  28148. * @param y defines the y coordinate of the origin (on-screen)
  28149. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28150. * @param camera defines the camera to use for the picking
  28151. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28152. * @returns a Ray
  28153. */
  28154. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28155. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28156. var result = BABYLON.Ray.Zero();
  28157. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28158. return result;
  28159. };
  28160. /**
  28161. * Creates a ray that can be used to pick in the scene
  28162. * @param x defines the x coordinate of the origin (on-screen)
  28163. * @param y defines the y coordinate of the origin (on-screen)
  28164. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28165. * @param result defines the ray where to store the picking ray
  28166. * @param camera defines the camera to use for the picking
  28167. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28168. * @returns the current scene
  28169. */
  28170. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28171. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28172. var engine = this._engine;
  28173. if (!camera) {
  28174. if (!this.activeCamera)
  28175. throw new Error("Active camera not set");
  28176. camera = this.activeCamera;
  28177. }
  28178. var cameraViewport = camera.viewport;
  28179. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28180. // Moving coordinates to local viewport world
  28181. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28182. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28183. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28184. return this;
  28185. };
  28186. /**
  28187. * Creates a ray that can be used to pick in the scene
  28188. * @param x defines the x coordinate of the origin (on-screen)
  28189. * @param y defines the y coordinate of the origin (on-screen)
  28190. * @param camera defines the camera to use for the picking
  28191. * @returns a Ray
  28192. */
  28193. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28194. var result = BABYLON.Ray.Zero();
  28195. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28196. return result;
  28197. };
  28198. /**
  28199. * Creates a ray that can be used to pick in the scene
  28200. * @param x defines the x coordinate of the origin (on-screen)
  28201. * @param y defines the y coordinate of the origin (on-screen)
  28202. * @param result defines the ray where to store the picking ray
  28203. * @param camera defines the camera to use for the picking
  28204. * @returns the current scene
  28205. */
  28206. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28207. if (!BABYLON.PickingInfo) {
  28208. return this;
  28209. }
  28210. var engine = this._engine;
  28211. if (!camera) {
  28212. if (!this.activeCamera)
  28213. throw new Error("Active camera not set");
  28214. camera = this.activeCamera;
  28215. }
  28216. var cameraViewport = camera.viewport;
  28217. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28218. var identity = BABYLON.Matrix.Identity();
  28219. // Moving coordinates to local viewport world
  28220. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28221. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28222. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28223. return this;
  28224. };
  28225. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28226. if (!BABYLON.PickingInfo) {
  28227. return null;
  28228. }
  28229. var pickingInfo = null;
  28230. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28231. var mesh = this.meshes[meshIndex];
  28232. if (predicate) {
  28233. if (!predicate(mesh)) {
  28234. continue;
  28235. }
  28236. }
  28237. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28238. continue;
  28239. }
  28240. var world = mesh.getWorldMatrix();
  28241. var ray = rayFunction(world);
  28242. var result = mesh.intersects(ray, fastCheck);
  28243. if (!result || !result.hit)
  28244. continue;
  28245. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28246. continue;
  28247. pickingInfo = result;
  28248. if (fastCheck) {
  28249. break;
  28250. }
  28251. }
  28252. return pickingInfo || new BABYLON.PickingInfo();
  28253. };
  28254. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28255. if (!BABYLON.PickingInfo) {
  28256. return null;
  28257. }
  28258. var pickingInfos = new Array();
  28259. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28260. var mesh = this.meshes[meshIndex];
  28261. if (predicate) {
  28262. if (!predicate(mesh)) {
  28263. continue;
  28264. }
  28265. }
  28266. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28267. continue;
  28268. }
  28269. var world = mesh.getWorldMatrix();
  28270. var ray = rayFunction(world);
  28271. var result = mesh.intersects(ray, false);
  28272. if (!result || !result.hit)
  28273. continue;
  28274. pickingInfos.push(result);
  28275. }
  28276. return pickingInfos;
  28277. };
  28278. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28279. if (!BABYLON.PickingInfo) {
  28280. return null;
  28281. }
  28282. var pickingInfo = null;
  28283. if (!camera) {
  28284. if (!this.activeCamera) {
  28285. return null;
  28286. }
  28287. camera = this.activeCamera;
  28288. }
  28289. if (this.spriteManagers.length > 0) {
  28290. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28291. var spriteManager = this.spriteManagers[spriteIndex];
  28292. if (!spriteManager.isPickable) {
  28293. continue;
  28294. }
  28295. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28296. if (!result || !result.hit)
  28297. continue;
  28298. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28299. continue;
  28300. pickingInfo = result;
  28301. if (fastCheck) {
  28302. break;
  28303. }
  28304. }
  28305. }
  28306. return pickingInfo || new BABYLON.PickingInfo();
  28307. };
  28308. /** Launch a ray to try to pick a mesh in the scene
  28309. * @param x position on screen
  28310. * @param y position on screen
  28311. * @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
  28312. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28313. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28314. * @returns a PickingInfo
  28315. */
  28316. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28317. var _this = this;
  28318. if (!BABYLON.PickingInfo) {
  28319. return null;
  28320. }
  28321. return this._internalPick(function (world) {
  28322. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28323. return _this._tempPickingRay;
  28324. }, predicate, fastCheck);
  28325. };
  28326. /** Launch a ray to try to pick a sprite in the scene
  28327. * @param x position on screen
  28328. * @param y position on screen
  28329. * @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
  28330. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28331. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28332. * @returns a PickingInfo
  28333. */
  28334. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28335. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28336. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28337. };
  28338. /** Use the given ray to pick a mesh in the scene
  28339. * @param ray The ray to use to pick meshes
  28340. * @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
  28341. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28342. * @returns a PickingInfo
  28343. */
  28344. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28345. var _this = this;
  28346. return this._internalPick(function (world) {
  28347. if (!_this._pickWithRayInverseMatrix) {
  28348. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28349. }
  28350. world.invertToRef(_this._pickWithRayInverseMatrix);
  28351. if (!_this._cachedRayForTransform) {
  28352. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28353. }
  28354. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28355. return _this._cachedRayForTransform;
  28356. }, predicate, fastCheck);
  28357. };
  28358. /**
  28359. * Launch a ray to try to pick a mesh in the scene
  28360. * @param x X position on screen
  28361. * @param y Y position on screen
  28362. * @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
  28363. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28364. * @returns an array of PickingInfo
  28365. */
  28366. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28367. var _this = this;
  28368. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28369. };
  28370. /**
  28371. * Launch a ray to try to pick a mesh in the scene
  28372. * @param ray Ray to use
  28373. * @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
  28374. * @returns an array of PickingInfo
  28375. */
  28376. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28377. var _this = this;
  28378. return this._internalMultiPick(function (world) {
  28379. if (!_this._pickWithRayInverseMatrix) {
  28380. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28381. }
  28382. world.invertToRef(_this._pickWithRayInverseMatrix);
  28383. if (!_this._cachedRayForTransform) {
  28384. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28385. }
  28386. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28387. return _this._cachedRayForTransform;
  28388. }, predicate);
  28389. };
  28390. /**
  28391. * Force the value of meshUnderPointer
  28392. * @param mesh defines the mesh to use
  28393. */
  28394. Scene.prototype.setPointerOverMesh = function (mesh) {
  28395. if (this._pointerOverMesh === mesh) {
  28396. return;
  28397. }
  28398. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28399. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28400. }
  28401. this._pointerOverMesh = mesh;
  28402. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28403. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28404. }
  28405. };
  28406. /**
  28407. * Gets the mesh under the pointer
  28408. * @returns a Mesh or null if no mesh is under the pointer
  28409. */
  28410. Scene.prototype.getPointerOverMesh = function () {
  28411. return this._pointerOverMesh;
  28412. };
  28413. /**
  28414. * Force the sprite under the pointer
  28415. * @param sprite defines the sprite to use
  28416. */
  28417. Scene.prototype.setPointerOverSprite = function (sprite) {
  28418. if (this._pointerOverSprite === sprite) {
  28419. return;
  28420. }
  28421. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28422. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28423. }
  28424. this._pointerOverSprite = sprite;
  28425. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28426. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28427. }
  28428. };
  28429. /**
  28430. * Gets the sprite under the pointer
  28431. * @returns a Sprite or null if no sprite is under the pointer
  28432. */
  28433. Scene.prototype.getPointerOverSprite = function () {
  28434. return this._pointerOverSprite;
  28435. };
  28436. // Physics
  28437. /**
  28438. * Gets the current physics engine
  28439. * @returns a PhysicsEngine or null if none attached
  28440. */
  28441. Scene.prototype.getPhysicsEngine = function () {
  28442. return this._physicsEngine;
  28443. };
  28444. /**
  28445. * Enables physics to the current scene
  28446. * @param gravity defines the scene's gravity for the physics engine
  28447. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28448. * @return a boolean indicating if the physics engine was initialized
  28449. */
  28450. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28451. if (gravity === void 0) { gravity = null; }
  28452. if (this._physicsEngine) {
  28453. return true;
  28454. }
  28455. try {
  28456. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28457. return true;
  28458. }
  28459. catch (e) {
  28460. BABYLON.Tools.Error(e.message);
  28461. return false;
  28462. }
  28463. };
  28464. /**
  28465. * Disables and disposes the physics engine associated with the scene
  28466. */
  28467. Scene.prototype.disablePhysicsEngine = function () {
  28468. if (!this._physicsEngine) {
  28469. return;
  28470. }
  28471. this._physicsEngine.dispose();
  28472. this._physicsEngine = null;
  28473. };
  28474. /**
  28475. * Gets a boolean indicating if there is an active physics engine
  28476. * @returns a boolean indicating if there is an active physics engine
  28477. */
  28478. Scene.prototype.isPhysicsEnabled = function () {
  28479. return this._physicsEngine !== undefined;
  28480. };
  28481. /**
  28482. * Deletes a physics compound impostor
  28483. * @param compound defines the compound to delete
  28484. */
  28485. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28486. var mesh = compound.parts[0].mesh;
  28487. if (mesh.physicsImpostor) {
  28488. mesh.physicsImpostor.dispose( /*true*/);
  28489. mesh.physicsImpostor = null;
  28490. }
  28491. };
  28492. // Misc.
  28493. /** @hidden */
  28494. Scene.prototype._rebuildGeometries = function () {
  28495. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28496. var geometry = _a[_i];
  28497. geometry._rebuild();
  28498. }
  28499. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28500. var mesh = _c[_b];
  28501. mesh._rebuild();
  28502. }
  28503. if (this.postProcessManager) {
  28504. this.postProcessManager._rebuild();
  28505. }
  28506. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28507. var layer = _e[_d];
  28508. layer._rebuild();
  28509. }
  28510. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28511. var effectLayer = _g[_f];
  28512. effectLayer._rebuild();
  28513. }
  28514. if (this._boundingBoxRenderer) {
  28515. this._boundingBoxRenderer._rebuild();
  28516. }
  28517. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28518. var system = _j[_h];
  28519. system.rebuild();
  28520. }
  28521. if (this._postProcessRenderPipelineManager) {
  28522. this._postProcessRenderPipelineManager._rebuild();
  28523. }
  28524. };
  28525. /** @hidden */
  28526. Scene.prototype._rebuildTextures = function () {
  28527. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28528. var texture = _a[_i];
  28529. texture._rebuild();
  28530. }
  28531. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28532. };
  28533. /**
  28534. * Creates a default light for the scene.
  28535. * @param replace Whether to replace the existing lights in the scene.
  28536. */
  28537. Scene.prototype.createDefaultLight = function (replace) {
  28538. if (replace === void 0) { replace = false; }
  28539. // Dispose existing light in replace mode.
  28540. if (replace) {
  28541. if (this.lights) {
  28542. for (var i = 0; i < this.lights.length; i++) {
  28543. this.lights[i].dispose();
  28544. }
  28545. }
  28546. }
  28547. // Light
  28548. if (this.lights.length === 0) {
  28549. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28550. }
  28551. };
  28552. /**
  28553. * Creates a default camera for the scene.
  28554. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28555. * @param replace Whether to replace the existing active camera in the scene.
  28556. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28557. */
  28558. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28559. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28560. if (replace === void 0) { replace = false; }
  28561. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28562. // Dispose existing camera in replace mode.
  28563. if (replace) {
  28564. if (this.activeCamera) {
  28565. this.activeCamera.dispose();
  28566. this.activeCamera = null;
  28567. }
  28568. }
  28569. // Camera
  28570. if (!this.activeCamera) {
  28571. var worldExtends = this.getWorldExtends();
  28572. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28573. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28574. var camera;
  28575. var radius = worldSize.length() * 1.5;
  28576. // empty scene scenario!
  28577. if (!isFinite(radius)) {
  28578. radius = 1;
  28579. worldCenter.copyFromFloats(0, 0, 0);
  28580. }
  28581. if (createArcRotateCamera) {
  28582. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28583. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28584. arcRotateCamera.wheelPrecision = 100 / radius;
  28585. camera = arcRotateCamera;
  28586. }
  28587. else {
  28588. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28589. freeCamera.setTarget(worldCenter);
  28590. camera = freeCamera;
  28591. }
  28592. camera.minZ = radius * 0.01;
  28593. camera.maxZ = radius * 1000;
  28594. camera.speed = radius * 0.2;
  28595. this.activeCamera = camera;
  28596. var canvas = this.getEngine().getRenderingCanvas();
  28597. if (attachCameraControls && canvas) {
  28598. camera.attachControl(canvas);
  28599. }
  28600. }
  28601. };
  28602. /**
  28603. * Creates a default camera and a default light
  28604. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28605. * @param replace defines if the camera and/or light will replace the existing ones
  28606. * @param attachCameraControls defines if attachControl will be called on the new camera
  28607. */
  28608. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28609. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28610. if (replace === void 0) { replace = false; }
  28611. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28612. this.createDefaultLight(replace);
  28613. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28614. };
  28615. /**
  28616. * Creates a new sky box
  28617. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28618. * @param environmentTexture defines the texture to use as environment texture
  28619. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28620. * @param scale defines the overall scale of the skybox
  28621. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28622. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28623. * @returns a new mesh holding the sky box
  28624. */
  28625. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28626. if (pbr === void 0) { pbr = false; }
  28627. if (scale === void 0) { scale = 1000; }
  28628. if (blur === void 0) { blur = 0; }
  28629. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28630. if (!environmentTexture) {
  28631. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28632. return null;
  28633. }
  28634. if (setGlobalEnvTexture) {
  28635. if (environmentTexture) {
  28636. this.environmentTexture = environmentTexture;
  28637. }
  28638. }
  28639. // Skybox
  28640. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28641. if (pbr) {
  28642. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28643. hdrSkyboxMaterial.backFaceCulling = false;
  28644. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28645. if (hdrSkyboxMaterial.reflectionTexture) {
  28646. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28647. }
  28648. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28649. hdrSkyboxMaterial.disableLighting = true;
  28650. hdrSkyboxMaterial.twoSidedLighting = true;
  28651. hdrSkybox.infiniteDistance = true;
  28652. hdrSkybox.material = hdrSkyboxMaterial;
  28653. }
  28654. else {
  28655. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28656. skyboxMaterial.backFaceCulling = false;
  28657. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28658. if (skyboxMaterial.reflectionTexture) {
  28659. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28660. }
  28661. skyboxMaterial.disableLighting = true;
  28662. hdrSkybox.infiniteDistance = true;
  28663. hdrSkybox.material = skyboxMaterial;
  28664. }
  28665. return hdrSkybox;
  28666. };
  28667. /**
  28668. * Creates a new environment
  28669. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28670. * @param options defines the options you can use to configure the environment
  28671. * @returns the new EnvironmentHelper
  28672. */
  28673. Scene.prototype.createDefaultEnvironment = function (options) {
  28674. if (BABYLON.EnvironmentHelper) {
  28675. return new BABYLON.EnvironmentHelper(options, this);
  28676. }
  28677. return null;
  28678. };
  28679. /**
  28680. * Creates a new VREXperienceHelper
  28681. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28682. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28683. * @returns a new VREXperienceHelper
  28684. */
  28685. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28686. if (webVROptions === void 0) { webVROptions = {}; }
  28687. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28688. };
  28689. // Tags
  28690. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28691. if (tagsQuery === undefined) {
  28692. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28693. return list;
  28694. }
  28695. var listByTags = [];
  28696. forEach = forEach || (function (item) { return; });
  28697. for (var i in list) {
  28698. var item = list[i];
  28699. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28700. listByTags.push(item);
  28701. forEach(item);
  28702. }
  28703. }
  28704. return listByTags;
  28705. };
  28706. /**
  28707. * Get a list of meshes by tags
  28708. * @param tagsQuery defines the tags query to use
  28709. * @param forEach defines a predicate used to filter results
  28710. * @returns an array of Mesh
  28711. */
  28712. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28713. return this._getByTags(this.meshes, tagsQuery, forEach);
  28714. };
  28715. /**
  28716. * Get a list of cameras by tags
  28717. * @param tagsQuery defines the tags query to use
  28718. * @param forEach defines a predicate used to filter results
  28719. * @returns an array of Camera
  28720. */
  28721. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28722. return this._getByTags(this.cameras, tagsQuery, forEach);
  28723. };
  28724. /**
  28725. * Get a list of lights by tags
  28726. * @param tagsQuery defines the tags query to use
  28727. * @param forEach defines a predicate used to filter results
  28728. * @returns an array of Light
  28729. */
  28730. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28731. return this._getByTags(this.lights, tagsQuery, forEach);
  28732. };
  28733. /**
  28734. * Get a list of materials by tags
  28735. * @param tagsQuery defines the tags query to use
  28736. * @param forEach defines a predicate used to filter results
  28737. * @returns an array of Material
  28738. */
  28739. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28740. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28741. };
  28742. /**
  28743. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28744. * This allowed control for front to back rendering or reversly depending of the special needs.
  28745. *
  28746. * @param renderingGroupId The rendering group id corresponding to its index
  28747. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28748. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28749. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28750. */
  28751. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28752. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28753. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28754. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28755. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28756. };
  28757. /**
  28758. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28759. *
  28760. * @param renderingGroupId The rendering group id corresponding to its index
  28761. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28762. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28763. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28764. */
  28765. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28766. if (depth === void 0) { depth = true; }
  28767. if (stencil === void 0) { stencil = true; }
  28768. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28769. };
  28770. /**
  28771. * Will flag all materials as dirty to trigger new shader compilation
  28772. * @param flag defines the flag used to specify which material part must be marked as dirty
  28773. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28774. */
  28775. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28776. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28777. var material = _a[_i];
  28778. if (predicate && !predicate(material)) {
  28779. continue;
  28780. }
  28781. material.markAsDirty(flag);
  28782. }
  28783. };
  28784. /** @hidden */
  28785. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28786. var _this = this;
  28787. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28788. this._activeRequests.push(request);
  28789. request.onCompleteObservable.add(function (request) {
  28790. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28791. });
  28792. return request;
  28793. };
  28794. /** @hidden */
  28795. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28796. var _this = this;
  28797. return new Promise(function (resolve, reject) {
  28798. _this._loadFile(url, function (data) {
  28799. resolve(data);
  28800. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28801. reject(exception);
  28802. });
  28803. });
  28804. };
  28805. // Statics
  28806. Scene._FOGMODE_NONE = 0;
  28807. Scene._FOGMODE_EXP = 1;
  28808. Scene._FOGMODE_EXP2 = 2;
  28809. Scene._FOGMODE_LINEAR = 3;
  28810. Scene._uniqueIdCounter = 0;
  28811. /**
  28812. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28813. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28814. */
  28815. Scene.MinDeltaTime = 1.0;
  28816. /**
  28817. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28818. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28819. */
  28820. Scene.MaxDeltaTime = 1000.0;
  28821. /** The distance in pixel that you have to move to prevent some events */
  28822. Scene.DragMovementThreshold = 10; // in pixels
  28823. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28824. Scene.LongPressDelay = 500; // in milliseconds
  28825. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28826. Scene.DoubleClickDelay = 300; // in milliseconds
  28827. /** If you need to check double click without raising a single click at first click, enable this flag */
  28828. Scene.ExclusiveDoubleClickMode = false;
  28829. return Scene;
  28830. }());
  28831. BABYLON.Scene = Scene;
  28832. })(BABYLON || (BABYLON = {}));
  28833. //# sourceMappingURL=babylon.scene.js.map
  28834. var BABYLON;
  28835. (function (BABYLON) {
  28836. /**
  28837. * Set of assets to keep when moving a scene into an asset container.
  28838. */
  28839. var KeepAssets = /** @class */ (function () {
  28840. function KeepAssets() {
  28841. /**
  28842. * Cameras to keep.
  28843. */
  28844. this.cameras = new Array();
  28845. /**
  28846. * Lights to keep.
  28847. */
  28848. this.lights = new Array();
  28849. /**
  28850. * Meshes to keep.
  28851. */
  28852. this.meshes = new Array();
  28853. /**
  28854. * Skeletons to keep.
  28855. */
  28856. this.skeletons = new Array();
  28857. /**
  28858. * ParticleSystems to keep.
  28859. */
  28860. this.particleSystems = new Array();
  28861. /**
  28862. * Animations to keep.
  28863. */
  28864. this.animations = new Array();
  28865. /**
  28866. * AnimationGroups to keep.
  28867. */
  28868. this.animationGroups = new Array();
  28869. /**
  28870. * MultiMaterials to keep.
  28871. */
  28872. this.multiMaterials = new Array();
  28873. /**
  28874. * Materials to keep.
  28875. */
  28876. this.materials = new Array();
  28877. /**
  28878. * MorphTargetManagers to keep.
  28879. */
  28880. this.morphTargetManagers = new Array();
  28881. /**
  28882. * Geometries to keep.
  28883. */
  28884. this.geometries = new Array();
  28885. /**
  28886. * TransformNodes to keep.
  28887. */
  28888. this.transformNodes = new Array();
  28889. /**
  28890. * LensFlareSystems to keep.
  28891. */
  28892. this.lensFlareSystems = new Array();
  28893. /**
  28894. * ShadowGenerators to keep.
  28895. */
  28896. this.shadowGenerators = new Array();
  28897. /**
  28898. * ActionManagers to keep.
  28899. */
  28900. this.actionManagers = new Array();
  28901. /**
  28902. * Sounds to keep.
  28903. */
  28904. this.sounds = new Array();
  28905. /**
  28906. * Textures to keep.
  28907. */
  28908. this.textures = new Array();
  28909. /**
  28910. * Effect layers to keep.
  28911. */
  28912. this.effectLayers = new Array();
  28913. }
  28914. return KeepAssets;
  28915. }());
  28916. BABYLON.KeepAssets = KeepAssets;
  28917. /**
  28918. * Container with a set of assets that can be added or removed from a scene.
  28919. */
  28920. var AssetContainer = /** @class */ (function () {
  28921. /**
  28922. * Instantiates an AssetContainer.
  28923. * @param scene The scene the AssetContainer belongs to.
  28924. */
  28925. function AssetContainer(scene) {
  28926. // Objects
  28927. /**
  28928. * Cameras populated in the container.
  28929. */
  28930. this.cameras = new Array();
  28931. /**
  28932. * Lights populated in the container.
  28933. */
  28934. this.lights = new Array();
  28935. /**
  28936. * Meshes populated in the container.
  28937. */
  28938. this.meshes = new Array();
  28939. /**
  28940. * Skeletons populated in the container.
  28941. */
  28942. this.skeletons = new Array();
  28943. /**
  28944. * ParticleSystems populated in the container.
  28945. */
  28946. this.particleSystems = new Array();
  28947. /**
  28948. * Animations populated in the container.
  28949. */
  28950. this.animations = new Array();
  28951. /**
  28952. * AnimationGroups populated in the container.
  28953. */
  28954. this.animationGroups = new Array();
  28955. /**
  28956. * MultiMaterials populated in the container.
  28957. */
  28958. this.multiMaterials = new Array();
  28959. /**
  28960. * Materials populated in the container.
  28961. */
  28962. this.materials = new Array();
  28963. /**
  28964. * MorphTargetManagers populated in the container.
  28965. */
  28966. this.morphTargetManagers = new Array();
  28967. /**
  28968. * Geometries populated in the container.
  28969. */
  28970. this.geometries = new Array();
  28971. /**
  28972. * TransformNodes populated in the container.
  28973. */
  28974. this.transformNodes = new Array();
  28975. /**
  28976. * LensFlareSystems populated in the container.
  28977. */
  28978. this.lensFlareSystems = new Array();
  28979. /**
  28980. * ShadowGenerators populated in the container.
  28981. */
  28982. this.shadowGenerators = new Array();
  28983. /**
  28984. * ActionManagers populated in the container.
  28985. */
  28986. this.actionManagers = new Array();
  28987. /**
  28988. * Sounds populated in the container.
  28989. */
  28990. this.sounds = new Array();
  28991. /**
  28992. * Textures populated in the container.
  28993. */
  28994. this.textures = new Array();
  28995. /**
  28996. * Effect layers populated in the container.
  28997. */
  28998. this.effectLayers = new Array();
  28999. this.scene = scene;
  29000. }
  29001. /**
  29002. * Adds all the assets from the container to the scene.
  29003. */
  29004. AssetContainer.prototype.addAllToScene = function () {
  29005. var _this = this;
  29006. this.cameras.forEach(function (o) {
  29007. _this.scene.addCamera(o);
  29008. });
  29009. this.lights.forEach(function (o) {
  29010. _this.scene.addLight(o);
  29011. });
  29012. this.meshes.forEach(function (o) {
  29013. _this.scene.addMesh(o);
  29014. });
  29015. this.skeletons.forEach(function (o) {
  29016. _this.scene.addSkeleton(o);
  29017. });
  29018. this.particleSystems.forEach(function (o) {
  29019. _this.scene.addParticleSystem(o);
  29020. });
  29021. this.animations.forEach(function (o) {
  29022. _this.scene.addAnimation(o);
  29023. });
  29024. this.animationGroups.forEach(function (o) {
  29025. _this.scene.addAnimationGroup(o);
  29026. });
  29027. this.multiMaterials.forEach(function (o) {
  29028. _this.scene.addMultiMaterial(o);
  29029. });
  29030. this.materials.forEach(function (o) {
  29031. _this.scene.addMaterial(o);
  29032. });
  29033. this.morphTargetManagers.forEach(function (o) {
  29034. _this.scene.addMorphTargetManager(o);
  29035. });
  29036. this.geometries.forEach(function (o) {
  29037. _this.scene.addGeometry(o);
  29038. });
  29039. this.transformNodes.forEach(function (o) {
  29040. _this.scene.addTransformNode(o);
  29041. });
  29042. this.lensFlareSystems.forEach(function (o) {
  29043. _this.scene.addLensFlareSystem(o);
  29044. });
  29045. this.actionManagers.forEach(function (o) {
  29046. _this.scene.addActionManager(o);
  29047. });
  29048. this.sounds.forEach(function (o) {
  29049. o.play();
  29050. o.autoplay = true;
  29051. _this.scene.mainSoundTrack.AddSound(o);
  29052. });
  29053. this.textures.forEach(function (o) {
  29054. _this.scene.addTexture(o);
  29055. });
  29056. this.effectLayers.forEach(function (o) {
  29057. _this.scene.addEffectLayer(o);
  29058. });
  29059. };
  29060. /**
  29061. * Removes all the assets in the container from the scene
  29062. */
  29063. AssetContainer.prototype.removeAllFromScene = function () {
  29064. var _this = this;
  29065. this.cameras.forEach(function (o) {
  29066. _this.scene.removeCamera(o);
  29067. });
  29068. this.lights.forEach(function (o) {
  29069. _this.scene.removeLight(o);
  29070. });
  29071. this.meshes.forEach(function (o) {
  29072. _this.scene.removeMesh(o);
  29073. });
  29074. this.skeletons.forEach(function (o) {
  29075. _this.scene.removeSkeleton(o);
  29076. });
  29077. this.particleSystems.forEach(function (o) {
  29078. _this.scene.removeParticleSystem(o);
  29079. });
  29080. this.animations.forEach(function (o) {
  29081. _this.scene.removeAnimation(o);
  29082. });
  29083. this.animationGroups.forEach(function (o) {
  29084. _this.scene.removeAnimationGroup(o);
  29085. });
  29086. this.multiMaterials.forEach(function (o) {
  29087. _this.scene.removeMultiMaterial(o);
  29088. });
  29089. this.materials.forEach(function (o) {
  29090. _this.scene.removeMaterial(o);
  29091. });
  29092. this.morphTargetManagers.forEach(function (o) {
  29093. _this.scene.removeMorphTargetManager(o);
  29094. });
  29095. this.geometries.forEach(function (o) {
  29096. _this.scene.removeGeometry(o);
  29097. });
  29098. this.transformNodes.forEach(function (o) {
  29099. _this.scene.removeTransformNode(o);
  29100. });
  29101. this.lensFlareSystems.forEach(function (o) {
  29102. _this.scene.removeLensFlareSystem(o);
  29103. });
  29104. this.actionManagers.forEach(function (o) {
  29105. _this.scene.removeActionManager(o);
  29106. });
  29107. this.sounds.forEach(function (o) {
  29108. o.stop();
  29109. o.autoplay = false;
  29110. _this.scene.mainSoundTrack.RemoveSound(o);
  29111. });
  29112. this.textures.forEach(function (o) {
  29113. _this.scene.removeTexture(o);
  29114. });
  29115. this.effectLayers.forEach(function (o) {
  29116. _this.scene.removeEffectLayer(o);
  29117. });
  29118. };
  29119. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29120. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29121. var asset = sourceAssets_1[_i];
  29122. var move = true;
  29123. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29124. var keepAsset = keepAssets_1[_a];
  29125. if (asset === keepAsset) {
  29126. move = false;
  29127. break;
  29128. }
  29129. }
  29130. if (move) {
  29131. targetAssets.push(asset);
  29132. }
  29133. }
  29134. };
  29135. /**
  29136. * Removes all the assets contained in the scene and adds them to the container.
  29137. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29138. */
  29139. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29140. if (keepAssets === undefined) {
  29141. keepAssets = new KeepAssets();
  29142. }
  29143. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29144. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29145. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29146. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29147. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29148. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29149. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29150. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29151. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29152. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29153. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29154. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29155. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29156. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29157. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29158. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29159. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29160. this.removeAllFromScene();
  29161. };
  29162. return AssetContainer;
  29163. }());
  29164. BABYLON.AssetContainer = AssetContainer;
  29165. })(BABYLON || (BABYLON = {}));
  29166. //# sourceMappingURL=babylon.assetContainer.js.map
  29167. var BABYLON;
  29168. (function (BABYLON) {
  29169. var Buffer = /** @class */ (function () {
  29170. /**
  29171. * Constructor
  29172. * @param engine the engine
  29173. * @param data the data to use for this buffer
  29174. * @param updatable whether the data is updatable
  29175. * @param stride the stride (optional)
  29176. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29177. * @param instanced whether the buffer is instanced (optional)
  29178. * @param useBytes set to true if the stride in in bytes (optional)
  29179. */
  29180. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29181. if (stride === void 0) { stride = 0; }
  29182. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29183. if (instanced === void 0) { instanced = false; }
  29184. if (useBytes === void 0) { useBytes = false; }
  29185. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29186. this._engine = engine.getScene().getEngine();
  29187. }
  29188. else {
  29189. this._engine = engine;
  29190. }
  29191. this._updatable = updatable;
  29192. this._instanced = instanced;
  29193. this._data = data;
  29194. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29195. if (!postponeInternalCreation) { // by default
  29196. this.create();
  29197. }
  29198. }
  29199. /**
  29200. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29201. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29202. * @param offset defines offset in the buffer (0 by default)
  29203. * @param size defines the size in floats of attributes (position is 3 for instance)
  29204. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29205. * @param instanced defines if the vertex buffer contains indexed data
  29206. * @param useBytes defines if the offset and stride are in bytes
  29207. * @returns the new vertex buffer
  29208. */
  29209. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29210. if (useBytes === void 0) { useBytes = false; }
  29211. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29212. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29213. // a lot of these parameters are ignored as they are overriden by the buffer
  29214. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29215. };
  29216. // Properties
  29217. Buffer.prototype.isUpdatable = function () {
  29218. return this._updatable;
  29219. };
  29220. Buffer.prototype.getData = function () {
  29221. return this._data;
  29222. };
  29223. Buffer.prototype.getBuffer = function () {
  29224. return this._buffer;
  29225. };
  29226. /**
  29227. * Gets the stride in float32 units (i.e. byte stride / 4).
  29228. * May not be an integer if the byte stride is not divisible by 4.
  29229. * DEPRECATED. Use byteStride instead.
  29230. * @returns the stride in float32 units
  29231. */
  29232. Buffer.prototype.getStrideSize = function () {
  29233. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29234. };
  29235. // Methods
  29236. Buffer.prototype.create = function (data) {
  29237. if (data === void 0) { data = null; }
  29238. if (!data && this._buffer) {
  29239. return; // nothing to do
  29240. }
  29241. data = data || this._data;
  29242. if (!data) {
  29243. return;
  29244. }
  29245. if (!this._buffer) { // create buffer
  29246. if (this._updatable) {
  29247. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29248. this._data = data;
  29249. }
  29250. else {
  29251. this._buffer = this._engine.createVertexBuffer(data);
  29252. }
  29253. }
  29254. else if (this._updatable) { // update buffer
  29255. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29256. this._data = data;
  29257. }
  29258. };
  29259. Buffer.prototype._rebuild = function () {
  29260. this._buffer = null;
  29261. this.create(this._data);
  29262. };
  29263. Buffer.prototype.update = function (data) {
  29264. this.create(data);
  29265. };
  29266. /**
  29267. * Updates the data directly.
  29268. * @param data the new data
  29269. * @param offset the new offset
  29270. * @param vertexCount the vertex count (optional)
  29271. * @param useBytes set to true if the offset is in bytes
  29272. */
  29273. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29274. if (useBytes === void 0) { useBytes = false; }
  29275. if (!this._buffer) {
  29276. return;
  29277. }
  29278. if (this._updatable) { // update buffer
  29279. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29280. this._data = null;
  29281. }
  29282. };
  29283. Buffer.prototype.dispose = function () {
  29284. if (!this._buffer) {
  29285. return;
  29286. }
  29287. if (this._engine._releaseBuffer(this._buffer)) {
  29288. this._buffer = null;
  29289. }
  29290. };
  29291. return Buffer;
  29292. }());
  29293. BABYLON.Buffer = Buffer;
  29294. })(BABYLON || (BABYLON = {}));
  29295. //# sourceMappingURL=babylon.buffer.js.map
  29296. var BABYLON;
  29297. (function (BABYLON) {
  29298. var VertexBuffer = /** @class */ (function () {
  29299. /**
  29300. * Constructor
  29301. * @param engine the engine
  29302. * @param data the data to use for this vertex buffer
  29303. * @param kind the vertex buffer kind
  29304. * @param updatable whether the data is updatable
  29305. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29306. * @param stride the stride (optional)
  29307. * @param instanced whether the buffer is instanced (optional)
  29308. * @param offset the offset of the data (optional)
  29309. * @param size the number of components (optional)
  29310. * @param type the type of the component (optional)
  29311. * @param normalized whether the data contains normalized data (optional)
  29312. * @param useBytes set to true if stride and offset are in bytes (optional)
  29313. */
  29314. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29315. if (normalized === void 0) { normalized = false; }
  29316. if (useBytes === void 0) { useBytes = false; }
  29317. if (data instanceof BABYLON.Buffer) {
  29318. this._buffer = data;
  29319. this._ownsBuffer = false;
  29320. }
  29321. else {
  29322. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29323. this._ownsBuffer = true;
  29324. }
  29325. this._kind = kind;
  29326. if (type == undefined) {
  29327. var data_1 = this.getData();
  29328. this.type = VertexBuffer.FLOAT;
  29329. if (data_1 instanceof Int8Array)
  29330. this.type = VertexBuffer.BYTE;
  29331. else if (data_1 instanceof Uint8Array)
  29332. this.type = VertexBuffer.UNSIGNED_BYTE;
  29333. else if (data_1 instanceof Int16Array)
  29334. this.type = VertexBuffer.SHORT;
  29335. else if (data_1 instanceof Uint16Array)
  29336. this.type = VertexBuffer.UNSIGNED_SHORT;
  29337. else if (data_1 instanceof Int32Array)
  29338. this.type = VertexBuffer.INT;
  29339. else if (data_1 instanceof Uint32Array)
  29340. this.type = VertexBuffer.UNSIGNED_INT;
  29341. }
  29342. else {
  29343. this.type = type;
  29344. }
  29345. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29346. if (useBytes) {
  29347. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29348. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29349. this.byteOffset = offset || 0;
  29350. }
  29351. else {
  29352. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29353. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29354. this.byteOffset = (offset || 0) * typeByteLength;
  29355. }
  29356. this.normalized = normalized;
  29357. this._instanced = instanced !== undefined ? instanced : false;
  29358. this._instanceDivisor = instanced ? 1 : 0;
  29359. }
  29360. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29361. /**
  29362. * Gets or sets the instance divisor when in instanced mode
  29363. */
  29364. get: function () {
  29365. return this._instanceDivisor;
  29366. },
  29367. set: function (value) {
  29368. this._instanceDivisor = value;
  29369. if (value == 0) {
  29370. this._instanced = false;
  29371. }
  29372. else {
  29373. this._instanced = true;
  29374. }
  29375. },
  29376. enumerable: true,
  29377. configurable: true
  29378. });
  29379. VertexBuffer.prototype._rebuild = function () {
  29380. if (!this._buffer) {
  29381. return;
  29382. }
  29383. this._buffer._rebuild();
  29384. };
  29385. /**
  29386. * Returns the kind of the VertexBuffer (string).
  29387. */
  29388. VertexBuffer.prototype.getKind = function () {
  29389. return this._kind;
  29390. };
  29391. // Properties
  29392. /**
  29393. * Boolean : is the VertexBuffer updatable ?
  29394. */
  29395. VertexBuffer.prototype.isUpdatable = function () {
  29396. return this._buffer.isUpdatable();
  29397. };
  29398. /**
  29399. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29400. */
  29401. VertexBuffer.prototype.getData = function () {
  29402. return this._buffer.getData();
  29403. };
  29404. /**
  29405. * Returns the WebGLBuffer associated to the VertexBuffer.
  29406. */
  29407. VertexBuffer.prototype.getBuffer = function () {
  29408. return this._buffer.getBuffer();
  29409. };
  29410. /**
  29411. * Returns the stride as a multiple of the type byte length.
  29412. * DEPRECATED. Use byteStride instead.
  29413. */
  29414. VertexBuffer.prototype.getStrideSize = function () {
  29415. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29416. };
  29417. /**
  29418. * Returns the offset as a multiple of the type byte length.
  29419. * DEPRECATED. Use byteOffset instead.
  29420. */
  29421. VertexBuffer.prototype.getOffset = function () {
  29422. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29423. };
  29424. /**
  29425. * Returns the number of components per vertex attribute (integer).
  29426. */
  29427. VertexBuffer.prototype.getSize = function () {
  29428. return this._size;
  29429. };
  29430. /**
  29431. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29432. */
  29433. VertexBuffer.prototype.getIsInstanced = function () {
  29434. return this._instanced;
  29435. };
  29436. /**
  29437. * Returns the instancing divisor, zero for non-instanced (integer).
  29438. */
  29439. VertexBuffer.prototype.getInstanceDivisor = function () {
  29440. return this._instanceDivisor;
  29441. };
  29442. // Methods
  29443. /**
  29444. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29445. * Returns the created WebGLBuffer.
  29446. */
  29447. VertexBuffer.prototype.create = function (data) {
  29448. return this._buffer.create(data);
  29449. };
  29450. /**
  29451. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29452. * This function will create a new buffer if the current one is not updatable
  29453. * Returns the updated WebGLBuffer.
  29454. */
  29455. VertexBuffer.prototype.update = function (data) {
  29456. return this._buffer.update(data);
  29457. };
  29458. /**
  29459. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29460. * Returns the directly updated WebGLBuffer.
  29461. * @param data the new data
  29462. * @param offset the new offset
  29463. * @param useBytes set to true if the offset is in bytes
  29464. */
  29465. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29466. if (useBytes === void 0) { useBytes = false; }
  29467. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29468. };
  29469. /**
  29470. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29471. */
  29472. VertexBuffer.prototype.dispose = function () {
  29473. if (this._ownsBuffer) {
  29474. this._buffer.dispose();
  29475. }
  29476. };
  29477. /**
  29478. * Enumerates each value of this vertex buffer as numbers.
  29479. * @param count the number of values to enumerate
  29480. * @param callback the callback function called for each value
  29481. */
  29482. VertexBuffer.prototype.forEach = function (count, callback) {
  29483. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29484. };
  29485. Object.defineProperty(VertexBuffer, "PositionKind", {
  29486. get: function () {
  29487. return VertexBuffer._PositionKind;
  29488. },
  29489. enumerable: true,
  29490. configurable: true
  29491. });
  29492. Object.defineProperty(VertexBuffer, "NormalKind", {
  29493. get: function () {
  29494. return VertexBuffer._NormalKind;
  29495. },
  29496. enumerable: true,
  29497. configurable: true
  29498. });
  29499. Object.defineProperty(VertexBuffer, "TangentKind", {
  29500. get: function () {
  29501. return VertexBuffer._TangentKind;
  29502. },
  29503. enumerable: true,
  29504. configurable: true
  29505. });
  29506. Object.defineProperty(VertexBuffer, "UVKind", {
  29507. get: function () {
  29508. return VertexBuffer._UVKind;
  29509. },
  29510. enumerable: true,
  29511. configurable: true
  29512. });
  29513. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29514. get: function () {
  29515. return VertexBuffer._UV2Kind;
  29516. },
  29517. enumerable: true,
  29518. configurable: true
  29519. });
  29520. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29521. get: function () {
  29522. return VertexBuffer._UV3Kind;
  29523. },
  29524. enumerable: true,
  29525. configurable: true
  29526. });
  29527. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29528. get: function () {
  29529. return VertexBuffer._UV4Kind;
  29530. },
  29531. enumerable: true,
  29532. configurable: true
  29533. });
  29534. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29535. get: function () {
  29536. return VertexBuffer._UV5Kind;
  29537. },
  29538. enumerable: true,
  29539. configurable: true
  29540. });
  29541. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29542. get: function () {
  29543. return VertexBuffer._UV6Kind;
  29544. },
  29545. enumerable: true,
  29546. configurable: true
  29547. });
  29548. Object.defineProperty(VertexBuffer, "ColorKind", {
  29549. get: function () {
  29550. return VertexBuffer._ColorKind;
  29551. },
  29552. enumerable: true,
  29553. configurable: true
  29554. });
  29555. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29556. get: function () {
  29557. return VertexBuffer._MatricesIndicesKind;
  29558. },
  29559. enumerable: true,
  29560. configurable: true
  29561. });
  29562. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29563. get: function () {
  29564. return VertexBuffer._MatricesWeightsKind;
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29570. get: function () {
  29571. return VertexBuffer._MatricesIndicesExtraKind;
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29577. get: function () {
  29578. return VertexBuffer._MatricesWeightsExtraKind;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. /**
  29584. * Deduces the stride given a kind.
  29585. * @param kind The kind string to deduce
  29586. * @returns The deduced stride
  29587. */
  29588. VertexBuffer.DeduceStride = function (kind) {
  29589. switch (kind) {
  29590. case VertexBuffer.UVKind:
  29591. case VertexBuffer.UV2Kind:
  29592. case VertexBuffer.UV3Kind:
  29593. case VertexBuffer.UV4Kind:
  29594. case VertexBuffer.UV5Kind:
  29595. case VertexBuffer.UV6Kind:
  29596. return 2;
  29597. case VertexBuffer.NormalKind:
  29598. case VertexBuffer.PositionKind:
  29599. return 3;
  29600. case VertexBuffer.ColorKind:
  29601. case VertexBuffer.MatricesIndicesKind:
  29602. case VertexBuffer.MatricesIndicesExtraKind:
  29603. case VertexBuffer.MatricesWeightsKind:
  29604. case VertexBuffer.MatricesWeightsExtraKind:
  29605. case VertexBuffer.TangentKind:
  29606. return 4;
  29607. default:
  29608. throw new Error("Invalid kind '" + kind + "'");
  29609. }
  29610. };
  29611. /**
  29612. * Gets the byte length of the given type.
  29613. * @param type the type
  29614. * @returns the number of bytes
  29615. */
  29616. VertexBuffer.GetTypeByteLength = function (type) {
  29617. switch (type) {
  29618. case VertexBuffer.BYTE:
  29619. case VertexBuffer.UNSIGNED_BYTE:
  29620. return 1;
  29621. case VertexBuffer.SHORT:
  29622. case VertexBuffer.UNSIGNED_SHORT:
  29623. return 2;
  29624. case VertexBuffer.INT:
  29625. case VertexBuffer.FLOAT:
  29626. return 4;
  29627. default:
  29628. throw new Error("Invalid type '" + type + "'");
  29629. }
  29630. };
  29631. /**
  29632. * Enumerates each value of the given parameters as numbers.
  29633. * @param data the data to enumerate
  29634. * @param byteOffset the byte offset of the data
  29635. * @param byteStride the byte stride of the data
  29636. * @param componentCount the number of components per element
  29637. * @param componentType the type of the component
  29638. * @param count the total number of components
  29639. * @param normalized whether the data is normalized
  29640. * @param callback the callback function called for each value
  29641. */
  29642. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29643. if (data instanceof Array) {
  29644. var offset = byteOffset / 4;
  29645. var stride = byteStride / 4;
  29646. for (var index = 0; index < count; index += componentCount) {
  29647. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29648. callback(data[offset + componentIndex], index + componentIndex);
  29649. }
  29650. offset += stride;
  29651. }
  29652. }
  29653. else {
  29654. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29655. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29656. for (var index = 0; index < count; index += componentCount) {
  29657. var componentByteOffset = byteOffset;
  29658. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29659. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29660. callback(value, index + componentIndex);
  29661. componentByteOffset += componentByteLength;
  29662. }
  29663. byteOffset += byteStride;
  29664. }
  29665. }
  29666. };
  29667. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29668. switch (type) {
  29669. case VertexBuffer.BYTE: {
  29670. var value = dataView.getInt8(byteOffset);
  29671. if (normalized) {
  29672. value = Math.max(value / 127, -1);
  29673. }
  29674. return value;
  29675. }
  29676. case VertexBuffer.UNSIGNED_BYTE: {
  29677. var value = dataView.getUint8(byteOffset);
  29678. if (normalized) {
  29679. value = value / 255;
  29680. }
  29681. return value;
  29682. }
  29683. case VertexBuffer.SHORT: {
  29684. var value = dataView.getInt16(byteOffset, true);
  29685. if (normalized) {
  29686. value = Math.max(value / 16383, -1);
  29687. }
  29688. return value;
  29689. }
  29690. case VertexBuffer.UNSIGNED_SHORT: {
  29691. var value = dataView.getUint16(byteOffset, true);
  29692. if (normalized) {
  29693. value = value / 65535;
  29694. }
  29695. return value;
  29696. }
  29697. case VertexBuffer.FLOAT: {
  29698. return dataView.getFloat32(byteOffset, true);
  29699. }
  29700. default: {
  29701. throw new Error("Invalid component type " + type);
  29702. }
  29703. }
  29704. };
  29705. /**
  29706. * The byte type.
  29707. */
  29708. VertexBuffer.BYTE = 5120;
  29709. /**
  29710. * The unsigned byte type.
  29711. */
  29712. VertexBuffer.UNSIGNED_BYTE = 5121;
  29713. /**
  29714. * The short type.
  29715. */
  29716. VertexBuffer.SHORT = 5122;
  29717. /**
  29718. * The unsigned short type.
  29719. */
  29720. VertexBuffer.UNSIGNED_SHORT = 5123;
  29721. /**
  29722. * The integer type.
  29723. */
  29724. VertexBuffer.INT = 5124;
  29725. /**
  29726. * The unsigned integer type.
  29727. */
  29728. VertexBuffer.UNSIGNED_INT = 5125;
  29729. /**
  29730. * The float type.
  29731. */
  29732. VertexBuffer.FLOAT = 5126;
  29733. // Enums
  29734. VertexBuffer._PositionKind = "position";
  29735. VertexBuffer._NormalKind = "normal";
  29736. VertexBuffer._TangentKind = "tangent";
  29737. VertexBuffer._UVKind = "uv";
  29738. VertexBuffer._UV2Kind = "uv2";
  29739. VertexBuffer._UV3Kind = "uv3";
  29740. VertexBuffer._UV4Kind = "uv4";
  29741. VertexBuffer._UV5Kind = "uv5";
  29742. VertexBuffer._UV6Kind = "uv6";
  29743. VertexBuffer._ColorKind = "color";
  29744. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29745. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29746. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29747. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29748. return VertexBuffer;
  29749. }());
  29750. BABYLON.VertexBuffer = VertexBuffer;
  29751. })(BABYLON || (BABYLON = {}));
  29752. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29753. var BABYLON;
  29754. (function (BABYLON) {
  29755. /**
  29756. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29757. */
  29758. var DummyInternalTextureTracker = /** @class */ (function () {
  29759. function DummyInternalTextureTracker() {
  29760. /**
  29761. * Gets or set the previous tracker in the list
  29762. */
  29763. this.previous = null;
  29764. /**
  29765. * Gets or set the next tracker in the list
  29766. */
  29767. this.next = null;
  29768. }
  29769. return DummyInternalTextureTracker;
  29770. }());
  29771. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29772. })(BABYLON || (BABYLON = {}));
  29773. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29774. var BABYLON;
  29775. (function (BABYLON) {
  29776. /**
  29777. * Class used to store data associated with WebGL texture data for the engine
  29778. * This class should not be used directly
  29779. */
  29780. var InternalTexture = /** @class */ (function () {
  29781. /**
  29782. * Creates a new InternalTexture
  29783. * @param engine defines the engine to use
  29784. * @param dataSource defines the type of data that will be used
  29785. */
  29786. function InternalTexture(engine, dataSource) {
  29787. /**
  29788. * Observable called when the texture is loaded
  29789. */
  29790. this.onLoadedObservable = new BABYLON.Observable();
  29791. /**
  29792. * Gets or set the previous tracker in the list
  29793. */
  29794. this.previous = null;
  29795. /**
  29796. * Gets or set the next tracker in the list
  29797. */
  29798. this.next = null;
  29799. // Private
  29800. /** @hidden */
  29801. this._initialSlot = -1;
  29802. /** @hidden */
  29803. this._designatedSlot = -1;
  29804. /** @hidden */
  29805. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29806. /** @hidden */
  29807. this._comparisonFunction = 0;
  29808. /** @hidden */
  29809. this._references = 1;
  29810. this._engine = engine;
  29811. this._dataSource = dataSource;
  29812. this._webGLTexture = engine._createTexture();
  29813. }
  29814. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29815. /**
  29816. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29817. */
  29818. get: function () {
  29819. return this._dataSource;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. /**
  29825. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29826. */
  29827. InternalTexture.prototype.incrementReferences = function () {
  29828. this._references++;
  29829. };
  29830. /**
  29831. * Change the size of the texture (not the size of the content)
  29832. * @param width defines the new width
  29833. * @param height defines the new height
  29834. * @param depth defines the new depth (1 by default)
  29835. */
  29836. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29837. if (depth === void 0) { depth = 1; }
  29838. this.width = width;
  29839. this.height = height;
  29840. this.depth = depth;
  29841. this.baseWidth = width;
  29842. this.baseHeight = height;
  29843. this.baseDepth = depth;
  29844. this._size = width * height * depth;
  29845. };
  29846. /** @hidden */
  29847. InternalTexture.prototype._rebuild = function () {
  29848. var _this = this;
  29849. var proxy;
  29850. this.isReady = false;
  29851. this._cachedCoordinatesMode = null;
  29852. this._cachedWrapU = null;
  29853. this._cachedWrapV = null;
  29854. this._cachedAnisotropicFilteringLevel = null;
  29855. switch (this._dataSource) {
  29856. case InternalTexture.DATASOURCE_TEMP:
  29857. return;
  29858. case InternalTexture.DATASOURCE_URL:
  29859. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29860. _this.isReady = true;
  29861. }, null, this._buffer, undefined, this.format);
  29862. proxy._swapAndDie(this);
  29863. return;
  29864. case InternalTexture.DATASOURCE_RAW:
  29865. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29866. proxy._swapAndDie(this);
  29867. this.isReady = true;
  29868. return;
  29869. case InternalTexture.DATASOURCE_RAW3D:
  29870. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29871. proxy._swapAndDie(this);
  29872. this.isReady = true;
  29873. return;
  29874. case InternalTexture.DATASOURCE_DYNAMIC:
  29875. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29876. proxy._swapAndDie(this);
  29877. // The engine will make sure to update content so no need to flag it as isReady = true
  29878. return;
  29879. case InternalTexture.DATASOURCE_RENDERTARGET:
  29880. var options = new BABYLON.RenderTargetCreationOptions();
  29881. options.generateDepthBuffer = this._generateDepthBuffer;
  29882. options.generateMipMaps = this.generateMipMaps;
  29883. options.generateStencilBuffer = this._generateStencilBuffer;
  29884. options.samplingMode = this.samplingMode;
  29885. options.type = this.type;
  29886. if (this.isCube) {
  29887. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29888. }
  29889. else {
  29890. var size = {
  29891. width: this.width,
  29892. height: this.height
  29893. };
  29894. proxy = this._engine.createRenderTargetTexture(size, options);
  29895. }
  29896. proxy._swapAndDie(this);
  29897. this.isReady = true;
  29898. return;
  29899. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29900. var depthTextureOptions = {
  29901. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29902. comparisonFunction: this._comparisonFunction,
  29903. generateStencil: this._generateStencilBuffer,
  29904. isCube: this.isCube
  29905. };
  29906. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29907. proxy._swapAndDie(this);
  29908. this.isReady = true;
  29909. return;
  29910. case InternalTexture.DATASOURCE_CUBE:
  29911. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29912. _this.isReady = true;
  29913. }, null, this.format, this._extension);
  29914. proxy._swapAndDie(this);
  29915. return;
  29916. case InternalTexture.DATASOURCE_CUBERAW:
  29917. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29918. proxy._swapAndDie(this);
  29919. this.isReady = true;
  29920. return;
  29921. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29922. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29923. if (proxy) {
  29924. proxy._swapAndDie(_this);
  29925. }
  29926. _this.isReady = true;
  29927. }, null, this.format, this._extension);
  29928. return;
  29929. }
  29930. };
  29931. InternalTexture.prototype._swapAndDie = function (target) {
  29932. target._webGLTexture = this._webGLTexture;
  29933. if (this._framebuffer) {
  29934. target._framebuffer = this._framebuffer;
  29935. }
  29936. if (this._depthStencilBuffer) {
  29937. target._depthStencilBuffer = this._depthStencilBuffer;
  29938. }
  29939. if (this._lodTextureHigh) {
  29940. if (target._lodTextureHigh) {
  29941. target._lodTextureHigh.dispose();
  29942. }
  29943. target._lodTextureHigh = this._lodTextureHigh;
  29944. }
  29945. if (this._lodTextureMid) {
  29946. if (target._lodTextureMid) {
  29947. target._lodTextureMid.dispose();
  29948. }
  29949. target._lodTextureMid = this._lodTextureMid;
  29950. }
  29951. if (this._lodTextureLow) {
  29952. if (target._lodTextureLow) {
  29953. target._lodTextureLow.dispose();
  29954. }
  29955. target._lodTextureLow = this._lodTextureLow;
  29956. }
  29957. var cache = this._engine.getLoadedTexturesCache();
  29958. var index = cache.indexOf(this);
  29959. if (index !== -1) {
  29960. cache.splice(index, 1);
  29961. }
  29962. };
  29963. /**
  29964. * Dispose the current allocated resources
  29965. */
  29966. InternalTexture.prototype.dispose = function () {
  29967. if (!this._webGLTexture) {
  29968. return;
  29969. }
  29970. this._references--;
  29971. if (this._references === 0) {
  29972. this._engine._releaseTexture(this);
  29973. this._webGLTexture = null;
  29974. this.previous = null;
  29975. this.next = null;
  29976. }
  29977. };
  29978. /**
  29979. * The source of the texture data is unknown
  29980. */
  29981. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29982. /**
  29983. * Texture data comes from an URL
  29984. */
  29985. InternalTexture.DATASOURCE_URL = 1;
  29986. /**
  29987. * Texture data is only used for temporary storage
  29988. */
  29989. InternalTexture.DATASOURCE_TEMP = 2;
  29990. /**
  29991. * Texture data comes from raw data (ArrayBuffer)
  29992. */
  29993. InternalTexture.DATASOURCE_RAW = 3;
  29994. /**
  29995. * Texture content is dynamic (video or dynamic texture)
  29996. */
  29997. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29998. /**
  29999. * Texture content is generated by rendering to it
  30000. */
  30001. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30002. /**
  30003. * Texture content is part of a multi render target process
  30004. */
  30005. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30006. /**
  30007. * Texture data comes from a cube data file
  30008. */
  30009. InternalTexture.DATASOURCE_CUBE = 7;
  30010. /**
  30011. * Texture data comes from a raw cube data
  30012. */
  30013. InternalTexture.DATASOURCE_CUBERAW = 8;
  30014. /**
  30015. * Texture data come from a prefiltered cube data file
  30016. */
  30017. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30018. /**
  30019. * Texture content is raw 3D data
  30020. */
  30021. InternalTexture.DATASOURCE_RAW3D = 10;
  30022. /**
  30023. * Texture content is a depth texture
  30024. */
  30025. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30026. return InternalTexture;
  30027. }());
  30028. BABYLON.InternalTexture = InternalTexture;
  30029. })(BABYLON || (BABYLON = {}));
  30030. //# sourceMappingURL=babylon.internalTexture.js.map
  30031. var BABYLON;
  30032. (function (BABYLON) {
  30033. var BaseTexture = /** @class */ (function () {
  30034. function BaseTexture(scene) {
  30035. this._hasAlpha = false;
  30036. this.getAlphaFromRGB = false;
  30037. this.level = 1;
  30038. this.coordinatesIndex = 0;
  30039. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30040. /**
  30041. * | Value | Type | Description |
  30042. * | ----- | ------------------ | ----------- |
  30043. * | 0 | CLAMP_ADDRESSMODE | |
  30044. * | 1 | WRAP_ADDRESSMODE | |
  30045. * | 2 | MIRROR_ADDRESSMODE | |
  30046. */
  30047. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30048. /**
  30049. * | Value | Type | Description |
  30050. * | ----- | ------------------ | ----------- |
  30051. * | 0 | CLAMP_ADDRESSMODE | |
  30052. * | 1 | WRAP_ADDRESSMODE | |
  30053. * | 2 | MIRROR_ADDRESSMODE | |
  30054. */
  30055. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30056. /**
  30057. * | Value | Type | Description |
  30058. * | ----- | ------------------ | ----------- |
  30059. * | 0 | CLAMP_ADDRESSMODE | |
  30060. * | 1 | WRAP_ADDRESSMODE | |
  30061. * | 2 | MIRROR_ADDRESSMODE | |
  30062. */
  30063. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30064. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30065. this.isCube = false;
  30066. this.is3D = false;
  30067. this.gammaSpace = true;
  30068. this.invertZ = false;
  30069. this.lodLevelInAlpha = false;
  30070. this.lodGenerationOffset = 0.0;
  30071. this.lodGenerationScale = 0.8;
  30072. this.isRenderTarget = false;
  30073. this.animations = new Array();
  30074. /**
  30075. * An event triggered when the texture is disposed.
  30076. */
  30077. this.onDisposeObservable = new BABYLON.Observable();
  30078. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30079. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30080. if (this._scene) {
  30081. this._scene.textures.push(this);
  30082. }
  30083. this._uid = null;
  30084. }
  30085. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30086. get: function () {
  30087. return this._hasAlpha;
  30088. },
  30089. set: function (value) {
  30090. if (this._hasAlpha === value) {
  30091. return;
  30092. }
  30093. this._hasAlpha = value;
  30094. if (this._scene) {
  30095. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30096. }
  30097. },
  30098. enumerable: true,
  30099. configurable: true
  30100. });
  30101. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30102. get: function () {
  30103. return this._coordinatesMode;
  30104. },
  30105. /**
  30106. * How a texture is mapped.
  30107. *
  30108. * | Value | Type | Description |
  30109. * | ----- | ----------------------------------- | ----------- |
  30110. * | 0 | EXPLICIT_MODE | |
  30111. * | 1 | SPHERICAL_MODE | |
  30112. * | 2 | PLANAR_MODE | |
  30113. * | 3 | CUBIC_MODE | |
  30114. * | 4 | PROJECTION_MODE | |
  30115. * | 5 | SKYBOX_MODE | |
  30116. * | 6 | INVCUBIC_MODE | |
  30117. * | 7 | EQUIRECTANGULAR_MODE | |
  30118. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30119. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30120. */
  30121. set: function (value) {
  30122. if (this._coordinatesMode === value) {
  30123. return;
  30124. }
  30125. this._coordinatesMode = value;
  30126. if (this._scene) {
  30127. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30128. }
  30129. },
  30130. enumerable: true,
  30131. configurable: true
  30132. });
  30133. Object.defineProperty(BaseTexture.prototype, "uid", {
  30134. get: function () {
  30135. if (!this._uid) {
  30136. this._uid = BABYLON.Tools.RandomId();
  30137. }
  30138. return this._uid;
  30139. },
  30140. enumerable: true,
  30141. configurable: true
  30142. });
  30143. BaseTexture.prototype.toString = function () {
  30144. return this.name;
  30145. };
  30146. BaseTexture.prototype.getClassName = function () {
  30147. return "BaseTexture";
  30148. };
  30149. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30150. set: function (callback) {
  30151. if (this._onDisposeObserver) {
  30152. this.onDisposeObservable.remove(this._onDisposeObserver);
  30153. }
  30154. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30160. get: function () {
  30161. return true;
  30162. },
  30163. enumerable: true,
  30164. configurable: true
  30165. });
  30166. BaseTexture.prototype.getScene = function () {
  30167. return this._scene;
  30168. };
  30169. BaseTexture.prototype.getTextureMatrix = function () {
  30170. return BABYLON.Matrix.IdentityReadOnly;
  30171. };
  30172. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30173. return BABYLON.Matrix.IdentityReadOnly;
  30174. };
  30175. BaseTexture.prototype.getInternalTexture = function () {
  30176. return this._texture;
  30177. };
  30178. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30179. return !this.isBlocking || this.isReady();
  30180. };
  30181. BaseTexture.prototype.isReady = function () {
  30182. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30183. this.delayLoad();
  30184. return false;
  30185. }
  30186. if (this._texture) {
  30187. return this._texture.isReady;
  30188. }
  30189. return false;
  30190. };
  30191. BaseTexture.prototype.getSize = function () {
  30192. if (this._texture && this._texture.width) {
  30193. return new BABYLON.Size(this._texture.width, this._texture.height);
  30194. }
  30195. if (this._texture && this._texture._size) {
  30196. return new BABYLON.Size(this._texture._size, this._texture._size);
  30197. }
  30198. return BABYLON.Size.Zero();
  30199. };
  30200. BaseTexture.prototype.getBaseSize = function () {
  30201. if (!this.isReady() || !this._texture)
  30202. return BABYLON.Size.Zero();
  30203. if (this._texture._size) {
  30204. return new BABYLON.Size(this._texture._size, this._texture._size);
  30205. }
  30206. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30207. };
  30208. BaseTexture.prototype.scale = function (ratio) {
  30209. };
  30210. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30211. get: function () {
  30212. return false;
  30213. },
  30214. enumerable: true,
  30215. configurable: true
  30216. });
  30217. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30218. if (!this._scene) {
  30219. return null;
  30220. }
  30221. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30222. for (var index = 0; index < texturesCache.length; index++) {
  30223. var texturesCacheEntry = texturesCache[index];
  30224. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30225. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30226. texturesCacheEntry.incrementReferences();
  30227. return texturesCacheEntry;
  30228. }
  30229. }
  30230. }
  30231. return null;
  30232. };
  30233. BaseTexture.prototype._rebuild = function () {
  30234. };
  30235. BaseTexture.prototype.delayLoad = function () {
  30236. };
  30237. BaseTexture.prototype.clone = function () {
  30238. return null;
  30239. };
  30240. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30241. get: function () {
  30242. if (!this._texture) {
  30243. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30244. }
  30245. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30246. },
  30247. enumerable: true,
  30248. configurable: true
  30249. });
  30250. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30251. get: function () {
  30252. if (!this._texture) {
  30253. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30254. }
  30255. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30256. },
  30257. enumerable: true,
  30258. configurable: true
  30259. });
  30260. BaseTexture.prototype.readPixels = function (faceIndex) {
  30261. if (faceIndex === void 0) { faceIndex = 0; }
  30262. if (!this._texture) {
  30263. return null;
  30264. }
  30265. var size = this.getSize();
  30266. var scene = this.getScene();
  30267. if (!scene) {
  30268. return null;
  30269. }
  30270. var engine = scene.getEngine();
  30271. if (this._texture.isCube) {
  30272. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30273. }
  30274. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30275. };
  30276. BaseTexture.prototype.releaseInternalTexture = function () {
  30277. if (this._texture) {
  30278. this._texture.dispose();
  30279. this._texture = null;
  30280. }
  30281. };
  30282. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30283. get: function () {
  30284. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30285. return null;
  30286. }
  30287. if (!this._texture._sphericalPolynomial) {
  30288. this._texture._sphericalPolynomial =
  30289. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30290. }
  30291. return this._texture._sphericalPolynomial;
  30292. },
  30293. set: function (value) {
  30294. if (this._texture) {
  30295. this._texture._sphericalPolynomial = value;
  30296. }
  30297. },
  30298. enumerable: true,
  30299. configurable: true
  30300. });
  30301. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30302. get: function () {
  30303. if (this._texture) {
  30304. return this._texture._lodTextureHigh;
  30305. }
  30306. return null;
  30307. },
  30308. enumerable: true,
  30309. configurable: true
  30310. });
  30311. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30312. get: function () {
  30313. if (this._texture) {
  30314. return this._texture._lodTextureMid;
  30315. }
  30316. return null;
  30317. },
  30318. enumerable: true,
  30319. configurable: true
  30320. });
  30321. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30322. get: function () {
  30323. if (this._texture) {
  30324. return this._texture._lodTextureLow;
  30325. }
  30326. return null;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. BaseTexture.prototype.dispose = function () {
  30332. if (!this._scene) {
  30333. return;
  30334. }
  30335. // Animations
  30336. this._scene.stopAnimation(this);
  30337. // Remove from scene
  30338. this._scene._removePendingData(this);
  30339. var index = this._scene.textures.indexOf(this);
  30340. if (index >= 0) {
  30341. this._scene.textures.splice(index, 1);
  30342. }
  30343. if (this._texture === undefined) {
  30344. return;
  30345. }
  30346. // Release
  30347. this.releaseInternalTexture();
  30348. // Callback
  30349. this.onDisposeObservable.notifyObservers(this);
  30350. this.onDisposeObservable.clear();
  30351. };
  30352. BaseTexture.prototype.serialize = function () {
  30353. if (!this.name) {
  30354. return null;
  30355. }
  30356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30357. // Animations
  30358. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30359. return serializationObject;
  30360. };
  30361. BaseTexture.WhenAllReady = function (textures, callback) {
  30362. var numRemaining = textures.length;
  30363. if (numRemaining === 0) {
  30364. callback();
  30365. return;
  30366. }
  30367. var _loop_1 = function () {
  30368. texture = textures[i];
  30369. if (texture.isReady()) {
  30370. if (--numRemaining === 0) {
  30371. callback();
  30372. }
  30373. }
  30374. else {
  30375. onLoadObservable = texture.onLoadObservable;
  30376. var onLoadCallback_1 = function () {
  30377. onLoadObservable.removeCallback(onLoadCallback_1);
  30378. if (--numRemaining === 0) {
  30379. callback();
  30380. }
  30381. };
  30382. onLoadObservable.add(onLoadCallback_1);
  30383. }
  30384. };
  30385. var texture, onLoadObservable;
  30386. for (var i = 0; i < textures.length; i++) {
  30387. _loop_1();
  30388. }
  30389. };
  30390. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], BaseTexture.prototype, "name", void 0);
  30394. __decorate([
  30395. BABYLON.serialize("hasAlpha")
  30396. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "level", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30406. __decorate([
  30407. BABYLON.serialize("coordinatesMode")
  30408. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "wrapU", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "wrapV", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "wrapR", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "isCube", void 0);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "is3D", void 0);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "gammaSpace", void 0);
  30430. __decorate([
  30431. BABYLON.serialize()
  30432. ], BaseTexture.prototype, "invertZ", void 0);
  30433. __decorate([
  30434. BABYLON.serialize()
  30435. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30436. __decorate([
  30437. BABYLON.serialize()
  30438. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30439. __decorate([
  30440. BABYLON.serialize()
  30441. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30442. __decorate([
  30443. BABYLON.serialize()
  30444. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30445. return BaseTexture;
  30446. }());
  30447. BABYLON.BaseTexture = BaseTexture;
  30448. })(BABYLON || (BABYLON = {}));
  30449. //# sourceMappingURL=babylon.baseTexture.js.map
  30450. var BABYLON;
  30451. (function (BABYLON) {
  30452. var Texture = /** @class */ (function (_super) {
  30453. __extends(Texture, _super);
  30454. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30455. if (noMipmap === void 0) { noMipmap = false; }
  30456. if (invertY === void 0) { invertY = true; }
  30457. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30458. if (onLoad === void 0) { onLoad = null; }
  30459. if (onError === void 0) { onError = null; }
  30460. if (buffer === void 0) { buffer = null; }
  30461. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30462. var _this = _super.call(this, scene) || this;
  30463. _this.uOffset = 0;
  30464. _this.vOffset = 0;
  30465. _this.uScale = 1.0;
  30466. _this.vScale = 1.0;
  30467. _this.uAng = 0;
  30468. _this.vAng = 0;
  30469. _this.wAng = 0;
  30470. _this._isBlocking = true;
  30471. _this.name = url || "";
  30472. _this.url = url;
  30473. _this._noMipmap = noMipmap;
  30474. _this._invertY = invertY;
  30475. _this._samplingMode = samplingMode;
  30476. _this._buffer = buffer;
  30477. _this._deleteBuffer = deleteBuffer;
  30478. if (format) {
  30479. _this._format = format;
  30480. }
  30481. scene = _this.getScene();
  30482. if (!scene) {
  30483. return _this;
  30484. }
  30485. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30486. var load = function () {
  30487. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30488. _this.onLoadObservable.notifyObservers(_this);
  30489. }
  30490. if (onLoad) {
  30491. onLoad();
  30492. }
  30493. if (!_this.isBlocking && scene) {
  30494. scene.resetCachedMaterial();
  30495. }
  30496. };
  30497. if (!_this.url) {
  30498. _this._delayedOnLoad = load;
  30499. _this._delayedOnError = onError;
  30500. return _this;
  30501. }
  30502. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30503. if (!_this._texture) {
  30504. if (!scene.useDelayedTextureLoading) {
  30505. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30506. if (deleteBuffer) {
  30507. delete _this._buffer;
  30508. }
  30509. }
  30510. else {
  30511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30512. _this._delayedOnLoad = load;
  30513. _this._delayedOnError = onError;
  30514. }
  30515. }
  30516. else {
  30517. if (_this._texture.isReady) {
  30518. BABYLON.Tools.SetImmediate(function () { return load(); });
  30519. }
  30520. else {
  30521. _this._texture.onLoadedObservable.add(load);
  30522. }
  30523. }
  30524. return _this;
  30525. }
  30526. Object.defineProperty(Texture.prototype, "noMipmap", {
  30527. get: function () {
  30528. return this._noMipmap;
  30529. },
  30530. enumerable: true,
  30531. configurable: true
  30532. });
  30533. Object.defineProperty(Texture.prototype, "isBlocking", {
  30534. get: function () {
  30535. return this._isBlocking;
  30536. },
  30537. set: function (value) {
  30538. this._isBlocking = value;
  30539. },
  30540. enumerable: true,
  30541. configurable: true
  30542. });
  30543. Object.defineProperty(Texture.prototype, "samplingMode", {
  30544. get: function () {
  30545. return this._samplingMode;
  30546. },
  30547. enumerable: true,
  30548. configurable: true
  30549. });
  30550. Texture.prototype.updateURL = function (url) {
  30551. this.url = url;
  30552. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30553. this.delayLoad();
  30554. };
  30555. Texture.prototype.delayLoad = function () {
  30556. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30557. return;
  30558. }
  30559. var scene = this.getScene();
  30560. if (!scene) {
  30561. return;
  30562. }
  30563. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30564. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30565. if (!this._texture) {
  30566. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30567. if (this._deleteBuffer) {
  30568. delete this._buffer;
  30569. }
  30570. }
  30571. else {
  30572. if (this._delayedOnLoad) {
  30573. if (this._texture.isReady) {
  30574. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30575. }
  30576. else {
  30577. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30578. }
  30579. }
  30580. }
  30581. this._delayedOnLoad = null;
  30582. this._delayedOnError = null;
  30583. };
  30584. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30585. if (!this._texture) {
  30586. return;
  30587. }
  30588. var scene = this.getScene();
  30589. if (!scene) {
  30590. return;
  30591. }
  30592. this._samplingMode = samplingMode;
  30593. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30594. };
  30595. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30596. x *= this.uScale;
  30597. y *= this.vScale;
  30598. x -= 0.5 * this.uScale;
  30599. y -= 0.5 * this.vScale;
  30600. z -= 0.5;
  30601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30602. t.x += 0.5 * this.uScale + this.uOffset;
  30603. t.y += 0.5 * this.vScale + this.vOffset;
  30604. t.z += 0.5;
  30605. };
  30606. Texture.prototype.getTextureMatrix = function () {
  30607. var _this = this;
  30608. if (this.uOffset === this._cachedUOffset &&
  30609. this.vOffset === this._cachedVOffset &&
  30610. this.uScale === this._cachedUScale &&
  30611. this.vScale === this._cachedVScale &&
  30612. this.uAng === this._cachedUAng &&
  30613. this.vAng === this._cachedVAng &&
  30614. this.wAng === this._cachedWAng) {
  30615. return this._cachedTextureMatrix;
  30616. }
  30617. this._cachedUOffset = this.uOffset;
  30618. this._cachedVOffset = this.vOffset;
  30619. this._cachedUScale = this.uScale;
  30620. this._cachedVScale = this.vScale;
  30621. this._cachedUAng = this.uAng;
  30622. this._cachedVAng = this.vAng;
  30623. this._cachedWAng = this.wAng;
  30624. if (!this._cachedTextureMatrix) {
  30625. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30626. this._rowGenerationMatrix = new BABYLON.Matrix();
  30627. this._t0 = BABYLON.Vector3.Zero();
  30628. this._t1 = BABYLON.Vector3.Zero();
  30629. this._t2 = BABYLON.Vector3.Zero();
  30630. }
  30631. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30632. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30633. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30634. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30635. this._t1.subtractInPlace(this._t0);
  30636. this._t2.subtractInPlace(this._t0);
  30637. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30638. this._cachedTextureMatrix.m[0] = this._t1.x;
  30639. this._cachedTextureMatrix.m[1] = this._t1.y;
  30640. this._cachedTextureMatrix.m[2] = this._t1.z;
  30641. this._cachedTextureMatrix.m[4] = this._t2.x;
  30642. this._cachedTextureMatrix.m[5] = this._t2.y;
  30643. this._cachedTextureMatrix.m[6] = this._t2.z;
  30644. this._cachedTextureMatrix.m[8] = this._t0.x;
  30645. this._cachedTextureMatrix.m[9] = this._t0.y;
  30646. this._cachedTextureMatrix.m[10] = this._t0.z;
  30647. var scene = this.getScene();
  30648. if (!scene) {
  30649. return this._cachedTextureMatrix;
  30650. }
  30651. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30652. return mat.hasTexture(_this);
  30653. });
  30654. return this._cachedTextureMatrix;
  30655. };
  30656. Texture.prototype.getReflectionTextureMatrix = function () {
  30657. var _this = this;
  30658. var scene = this.getScene();
  30659. if (!scene) {
  30660. return this._cachedTextureMatrix;
  30661. }
  30662. if (this.uOffset === this._cachedUOffset &&
  30663. this.vOffset === this._cachedVOffset &&
  30664. this.uScale === this._cachedUScale &&
  30665. this.vScale === this._cachedVScale &&
  30666. this.coordinatesMode === this._cachedCoordinatesMode) {
  30667. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30668. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30669. return this._cachedTextureMatrix;
  30670. }
  30671. }
  30672. else {
  30673. return this._cachedTextureMatrix;
  30674. }
  30675. }
  30676. if (!this._cachedTextureMatrix) {
  30677. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30678. }
  30679. if (!this._projectionModeMatrix) {
  30680. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30681. }
  30682. this._cachedUOffset = this.uOffset;
  30683. this._cachedVOffset = this.vOffset;
  30684. this._cachedUScale = this.uScale;
  30685. this._cachedVScale = this.vScale;
  30686. this._cachedCoordinatesMode = this.coordinatesMode;
  30687. switch (this.coordinatesMode) {
  30688. case Texture.PLANAR_MODE:
  30689. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30690. this._cachedTextureMatrix[0] = this.uScale;
  30691. this._cachedTextureMatrix[5] = this.vScale;
  30692. this._cachedTextureMatrix[12] = this.uOffset;
  30693. this._cachedTextureMatrix[13] = this.vOffset;
  30694. break;
  30695. case Texture.PROJECTION_MODE:
  30696. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30697. this._projectionModeMatrix.m[0] = 0.5;
  30698. this._projectionModeMatrix.m[5] = -0.5;
  30699. this._projectionModeMatrix.m[10] = 0.0;
  30700. this._projectionModeMatrix.m[12] = 0.5;
  30701. this._projectionModeMatrix.m[13] = 0.5;
  30702. this._projectionModeMatrix.m[14] = 1.0;
  30703. this._projectionModeMatrix.m[15] = 1.0;
  30704. var projectionMatrix = scene.getProjectionMatrix();
  30705. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30706. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30707. break;
  30708. default:
  30709. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30710. break;
  30711. }
  30712. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30713. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30714. });
  30715. return this._cachedTextureMatrix;
  30716. };
  30717. Texture.prototype.clone = function () {
  30718. var _this = this;
  30719. return BABYLON.SerializationHelper.Clone(function () {
  30720. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30721. }, this);
  30722. };
  30723. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30724. get: function () {
  30725. if (!this._onLoadObservable) {
  30726. this._onLoadObservable = new BABYLON.Observable();
  30727. }
  30728. return this._onLoadObservable;
  30729. },
  30730. enumerable: true,
  30731. configurable: true
  30732. });
  30733. Texture.prototype.serialize = function () {
  30734. var serializationObject = _super.prototype.serialize.call(this);
  30735. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30736. serializationObject.base64String = this._buffer;
  30737. serializationObject.name = serializationObject.name.replace("data:", "");
  30738. }
  30739. serializationObject.invertY = this._invertY;
  30740. serializationObject.samplingMode = this.samplingMode;
  30741. return serializationObject;
  30742. };
  30743. Texture.prototype.getClassName = function () {
  30744. return "Texture";
  30745. };
  30746. Texture.prototype.dispose = function () {
  30747. _super.prototype.dispose.call(this);
  30748. if (this.onLoadObservable) {
  30749. this.onLoadObservable.clear();
  30750. this._onLoadObservable = null;
  30751. }
  30752. this._delayedOnLoad = null;
  30753. this._delayedOnError = null;
  30754. };
  30755. // Statics
  30756. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30757. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30758. if (onLoad === void 0) { onLoad = null; }
  30759. if (onError === void 0) { onError = null; }
  30760. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30761. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30762. };
  30763. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30764. if (parsedTexture.customType) {
  30765. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30766. // Update Sampling Mode
  30767. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30768. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30769. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30770. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30771. }
  30772. }
  30773. return parsedCustomTexture;
  30774. }
  30775. if (parsedTexture.isCube) {
  30776. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30777. }
  30778. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30779. return null;
  30780. }
  30781. var texture = BABYLON.SerializationHelper.Parse(function () {
  30782. var generateMipMaps = true;
  30783. if (parsedTexture.noMipmap) {
  30784. generateMipMaps = false;
  30785. }
  30786. if (parsedTexture.mirrorPlane) {
  30787. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30788. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30789. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30790. return mirrorTexture;
  30791. }
  30792. else if (parsedTexture.isRenderTarget) {
  30793. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30794. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30795. return renderTargetTexture;
  30796. }
  30797. else {
  30798. var texture;
  30799. if (parsedTexture.base64String) {
  30800. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30801. }
  30802. else {
  30803. var url = rootUrl + parsedTexture.name;
  30804. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30805. url = parsedTexture.url;
  30806. }
  30807. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30808. }
  30809. return texture;
  30810. }
  30811. }, parsedTexture, scene);
  30812. // Update Sampling Mode
  30813. if (parsedTexture.samplingMode) {
  30814. var sampling = parsedTexture.samplingMode;
  30815. if (texture._samplingMode !== sampling) {
  30816. texture.updateSamplingMode(sampling);
  30817. }
  30818. }
  30819. // Animations
  30820. if (parsedTexture.animations) {
  30821. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30822. var parsedAnimation = parsedTexture.animations[animationIndex];
  30823. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30824. }
  30825. }
  30826. return texture;
  30827. };
  30828. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30829. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30830. if (noMipmap === void 0) { noMipmap = false; }
  30831. if (invertY === void 0) { invertY = true; }
  30832. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30833. if (onLoad === void 0) { onLoad = null; }
  30834. if (onError === void 0) { onError = null; }
  30835. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30836. if (name.substr(0, 5) !== "data:") {
  30837. name = "data:" + name;
  30838. }
  30839. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30840. };
  30841. // Constants
  30842. Texture.NEAREST_SAMPLINGMODE = 1;
  30843. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30844. Texture.BILINEAR_SAMPLINGMODE = 2;
  30845. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30846. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30847. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30848. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30849. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30850. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30851. Texture.NEAREST_LINEAR = 7;
  30852. Texture.NEAREST_NEAREST = 8;
  30853. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30854. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30855. Texture.LINEAR_LINEAR = 11;
  30856. Texture.LINEAR_NEAREST = 12;
  30857. Texture.EXPLICIT_MODE = 0;
  30858. Texture.SPHERICAL_MODE = 1;
  30859. Texture.PLANAR_MODE = 2;
  30860. Texture.CUBIC_MODE = 3;
  30861. Texture.PROJECTION_MODE = 4;
  30862. Texture.SKYBOX_MODE = 5;
  30863. Texture.INVCUBIC_MODE = 6;
  30864. Texture.EQUIRECTANGULAR_MODE = 7;
  30865. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30866. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30867. Texture.CLAMP_ADDRESSMODE = 0;
  30868. Texture.WRAP_ADDRESSMODE = 1;
  30869. Texture.MIRROR_ADDRESSMODE = 2;
  30870. /**
  30871. * 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
  30872. */
  30873. Texture.UseSerializedUrlIfAny = false;
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], Texture.prototype, "url", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], Texture.prototype, "uOffset", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], Texture.prototype, "vOffset", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], Texture.prototype, "uScale", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], Texture.prototype, "vScale", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], Texture.prototype, "uAng", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], Texture.prototype, "vAng", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], Texture.prototype, "wAng", void 0);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], Texture.prototype, "isBlocking", null);
  30901. return Texture;
  30902. }(BABYLON.BaseTexture));
  30903. BABYLON.Texture = Texture;
  30904. })(BABYLON || (BABYLON = {}));
  30905. //# sourceMappingURL=babylon.texture.js.map
  30906. var BABYLON;
  30907. (function (BABYLON) {
  30908. /**
  30909. * @hidden
  30910. **/
  30911. var _InstancesBatch = /** @class */ (function () {
  30912. function _InstancesBatch() {
  30913. this.mustReturn = false;
  30914. this.visibleInstances = new Array();
  30915. this.renderSelf = new Array();
  30916. }
  30917. return _InstancesBatch;
  30918. }());
  30919. BABYLON._InstancesBatch = _InstancesBatch;
  30920. var Mesh = /** @class */ (function (_super) {
  30921. __extends(Mesh, _super);
  30922. /**
  30923. * @constructor
  30924. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30925. * @param {Scene} scene The scene to add this mesh to.
  30926. * @param {Node} parent The parent of this mesh, if it has one
  30927. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30928. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30929. * When false, achieved by calling a clone(), also passing False.
  30930. * This will make creation of children, recursive.
  30931. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30932. */
  30933. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30934. if (scene === void 0) { scene = null; }
  30935. if (parent === void 0) { parent = null; }
  30936. if (source === void 0) { source = null; }
  30937. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30938. var _this = _super.call(this, name, scene) || this;
  30939. // Events
  30940. /**
  30941. * An event triggered before rendering the mesh
  30942. */
  30943. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30944. /**
  30945. * An event triggered after rendering the mesh
  30946. */
  30947. _this.onAfterRenderObservable = new BABYLON.Observable();
  30948. /**
  30949. * An event triggered before drawing the mesh
  30950. */
  30951. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30952. // Members
  30953. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30954. _this.instances = new Array();
  30955. _this._LODLevels = new Array();
  30956. _this._visibleInstances = {};
  30957. _this._renderIdForInstances = new Array();
  30958. _this._batchCache = new _InstancesBatch();
  30959. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30960. // Use by builder only to know what orientation were the mesh build in.
  30961. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30962. _this.overrideMaterialSideOrientation = null;
  30963. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30964. // Will be used to save a source mesh reference, If any
  30965. _this._source = null;
  30966. scene = _this.getScene();
  30967. if (source) {
  30968. // Source mesh
  30969. _this._source = source;
  30970. // Geometry
  30971. if (source._geometry) {
  30972. source._geometry.applyToMesh(_this);
  30973. }
  30974. // Deep copy
  30975. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30976. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30977. // Metadata
  30978. if (source.metadata && source.metadata.clone) {
  30979. _this.metadata = source.metadata.clone();
  30980. }
  30981. else {
  30982. _this.metadata = source.metadata;
  30983. }
  30984. // Tags
  30985. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30986. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30987. }
  30988. // Parent
  30989. _this.parent = source.parent;
  30990. // Pivot
  30991. _this.setPivotMatrix(source.getPivotMatrix());
  30992. _this.id = name + "." + source.id;
  30993. // Material
  30994. _this.material = source.material;
  30995. var index;
  30996. if (!doNotCloneChildren) {
  30997. // Children
  30998. var directDescendants = source.getDescendants(true);
  30999. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31000. var child = directDescendants[index_1];
  31001. if (child.clone) {
  31002. child.clone(name + "." + child.name, _this);
  31003. }
  31004. }
  31005. }
  31006. // Physics clone
  31007. var physicsEngine = _this.getScene().getPhysicsEngine();
  31008. if (clonePhysicsImpostor && physicsEngine) {
  31009. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31010. if (impostor) {
  31011. _this.physicsImpostor = impostor.clone(_this);
  31012. }
  31013. }
  31014. // Particles
  31015. for (index = 0; index < scene.particleSystems.length; index++) {
  31016. var system = scene.particleSystems[index];
  31017. if (system.emitter === source) {
  31018. system.clone(system.name, _this);
  31019. }
  31020. }
  31021. _this.computeWorldMatrix(true);
  31022. }
  31023. // Parent
  31024. if (parent !== null) {
  31025. _this.parent = parent;
  31026. }
  31027. return _this;
  31028. }
  31029. Object.defineProperty(Mesh, "FRONTSIDE", {
  31030. /**
  31031. * Mesh side orientation : usually the external or front surface
  31032. */
  31033. get: function () {
  31034. return Mesh._FRONTSIDE;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. Object.defineProperty(Mesh, "BACKSIDE", {
  31040. /**
  31041. * Mesh side orientation : usually the internal or back surface
  31042. */
  31043. get: function () {
  31044. return Mesh._BACKSIDE;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31050. /**
  31051. * Mesh side orientation : both internal and external or front and back surfaces
  31052. */
  31053. get: function () {
  31054. return Mesh._DOUBLESIDE;
  31055. },
  31056. enumerable: true,
  31057. configurable: true
  31058. });
  31059. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31060. /**
  31061. * Mesh side orientation : by default, `FRONTSIDE`
  31062. */
  31063. get: function () {
  31064. return Mesh._DEFAULTSIDE;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(Mesh, "NO_CAP", {
  31070. /**
  31071. * Mesh cap setting : no cap
  31072. */
  31073. get: function () {
  31074. return Mesh._NO_CAP;
  31075. },
  31076. enumerable: true,
  31077. configurable: true
  31078. });
  31079. Object.defineProperty(Mesh, "CAP_START", {
  31080. /**
  31081. * Mesh cap setting : one cap at the beginning of the mesh
  31082. */
  31083. get: function () {
  31084. return Mesh._CAP_START;
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. Object.defineProperty(Mesh, "CAP_END", {
  31090. /**
  31091. * Mesh cap setting : one cap at the end of the mesh
  31092. */
  31093. get: function () {
  31094. return Mesh._CAP_END;
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. Object.defineProperty(Mesh, "CAP_ALL", {
  31100. /**
  31101. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31102. */
  31103. get: function () {
  31104. return Mesh._CAP_ALL;
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31110. set: function (callback) {
  31111. if (this._onBeforeDrawObserver) {
  31112. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31113. }
  31114. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31120. get: function () {
  31121. return this._morphTargetManager;
  31122. },
  31123. set: function (value) {
  31124. if (this._morphTargetManager === value) {
  31125. return;
  31126. }
  31127. this._morphTargetManager = value;
  31128. this._syncGeometryWithMorphTargetManager();
  31129. },
  31130. enumerable: true,
  31131. configurable: true
  31132. });
  31133. Object.defineProperty(Mesh.prototype, "source", {
  31134. get: function () {
  31135. return this._source;
  31136. },
  31137. enumerable: true,
  31138. configurable: true
  31139. });
  31140. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31141. get: function () {
  31142. return this._unIndexed;
  31143. },
  31144. set: function (value) {
  31145. if (this._unIndexed !== value) {
  31146. this._unIndexed = value;
  31147. this._markSubMeshesAsAttributesDirty();
  31148. }
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. // Methods
  31154. /**
  31155. * Returns the string "Mesh".
  31156. */
  31157. Mesh.prototype.getClassName = function () {
  31158. return "Mesh";
  31159. };
  31160. /**
  31161. * Returns a string.
  31162. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31163. */
  31164. Mesh.prototype.toString = function (fullDetails) {
  31165. var ret = _super.prototype.toString.call(this, fullDetails);
  31166. ret += ", n vertices: " + this.getTotalVertices();
  31167. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31168. if (this.animations) {
  31169. for (var i = 0; i < this.animations.length; i++) {
  31170. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31171. }
  31172. }
  31173. if (fullDetails) {
  31174. if (this._geometry) {
  31175. var ib = this.getIndices();
  31176. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31177. if (vb && ib) {
  31178. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31179. }
  31180. }
  31181. else {
  31182. ret += ", flat shading: UNKNOWN";
  31183. }
  31184. }
  31185. return ret;
  31186. };
  31187. Mesh.prototype._unBindEffect = function () {
  31188. _super.prototype._unBindEffect.call(this);
  31189. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31190. var instance = _a[_i];
  31191. instance._unBindEffect();
  31192. }
  31193. };
  31194. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31195. /**
  31196. * True if the mesh has some Levels Of Details (LOD).
  31197. * Returns a boolean.
  31198. */
  31199. get: function () {
  31200. return this._LODLevels.length > 0;
  31201. },
  31202. enumerable: true,
  31203. configurable: true
  31204. });
  31205. /**
  31206. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31207. * @returns an array of {BABYLON.MeshLODLevel}
  31208. */
  31209. Mesh.prototype.getLODLevels = function () {
  31210. return this._LODLevels;
  31211. };
  31212. Mesh.prototype._sortLODLevels = function () {
  31213. this._LODLevels.sort(function (a, b) {
  31214. if (a.distance < b.distance) {
  31215. return 1;
  31216. }
  31217. if (a.distance > b.distance) {
  31218. return -1;
  31219. }
  31220. return 0;
  31221. });
  31222. };
  31223. /**
  31224. * Add a mesh as LOD level triggered at the given distance.
  31225. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31226. * @param {number} distance The distance from the center of the object to show this level
  31227. * @param {Mesh} mesh The mesh to be added as LOD level
  31228. * @return {Mesh} This mesh (for chaining)
  31229. */
  31230. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31231. if (mesh && mesh._masterMesh) {
  31232. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31233. return this;
  31234. }
  31235. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31236. this._LODLevels.push(level);
  31237. if (mesh) {
  31238. mesh._masterMesh = this;
  31239. }
  31240. this._sortLODLevels();
  31241. return this;
  31242. };
  31243. /**
  31244. * Returns the LOD level mesh at the passed distance or null if not found.
  31245. * It is related to the method `addLODLevel(distance, mesh)`.
  31246. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31247. * Returns an object Mesh or `null`.
  31248. */
  31249. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31250. for (var index = 0; index < this._LODLevels.length; index++) {
  31251. var level = this._LODLevels[index];
  31252. if (level.distance === distance) {
  31253. return level.mesh;
  31254. }
  31255. }
  31256. return null;
  31257. };
  31258. /**
  31259. * Remove a mesh from the LOD array
  31260. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31261. * @param {Mesh} mesh The mesh to be removed.
  31262. * @return {Mesh} This mesh (for chaining)
  31263. */
  31264. Mesh.prototype.removeLODLevel = function (mesh) {
  31265. for (var index = 0; index < this._LODLevels.length; index++) {
  31266. if (this._LODLevels[index].mesh === mesh) {
  31267. this._LODLevels.splice(index, 1);
  31268. if (mesh) {
  31269. mesh._masterMesh = null;
  31270. }
  31271. }
  31272. }
  31273. this._sortLODLevels();
  31274. return this;
  31275. };
  31276. /**
  31277. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31278. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31279. */
  31280. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31281. if (!this._LODLevels || this._LODLevels.length === 0) {
  31282. return this;
  31283. }
  31284. var bSphere;
  31285. if (boundingSphere) {
  31286. bSphere = boundingSphere;
  31287. }
  31288. else {
  31289. var boundingInfo = this.getBoundingInfo();
  31290. bSphere = boundingInfo.boundingSphere;
  31291. }
  31292. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31293. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31294. if (this.onLODLevelSelection) {
  31295. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31296. }
  31297. return this;
  31298. }
  31299. for (var index = 0; index < this._LODLevels.length; index++) {
  31300. var level = this._LODLevels[index];
  31301. if (level.distance < distanceToCamera) {
  31302. if (level.mesh) {
  31303. level.mesh._preActivate();
  31304. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31305. }
  31306. if (this.onLODLevelSelection) {
  31307. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31308. }
  31309. return level.mesh;
  31310. }
  31311. }
  31312. if (this.onLODLevelSelection) {
  31313. this.onLODLevelSelection(distanceToCamera, this, this);
  31314. }
  31315. return this;
  31316. };
  31317. Object.defineProperty(Mesh.prototype, "geometry", {
  31318. /**
  31319. * Returns the mesh internal Geometry object.
  31320. */
  31321. get: function () {
  31322. return this._geometry;
  31323. },
  31324. enumerable: true,
  31325. configurable: true
  31326. });
  31327. /**
  31328. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31329. */
  31330. Mesh.prototype.getTotalVertices = function () {
  31331. if (this._geometry === null || this._geometry === undefined) {
  31332. return 0;
  31333. }
  31334. return this._geometry.getTotalVertices();
  31335. };
  31336. /**
  31337. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31338. * 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.
  31339. * You can force the copy with forceCopy === true
  31340. * Returns null if the mesh has no geometry or no vertex buffer.
  31341. * Possible `kind` values :
  31342. * - BABYLON.VertexBuffer.PositionKind
  31343. * - BABYLON.VertexBuffer.UVKind
  31344. * - BABYLON.VertexBuffer.UV2Kind
  31345. * - BABYLON.VertexBuffer.UV3Kind
  31346. * - BABYLON.VertexBuffer.UV4Kind
  31347. * - BABYLON.VertexBuffer.UV5Kind
  31348. * - BABYLON.VertexBuffer.UV6Kind
  31349. * - BABYLON.VertexBuffer.ColorKind
  31350. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31351. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31352. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31353. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31354. */
  31355. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31356. if (!this._geometry) {
  31357. return null;
  31358. }
  31359. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31360. };
  31361. /**
  31362. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31363. * Returns `null` if the mesh has no geometry.
  31364. * Possible `kind` values :
  31365. * - BABYLON.VertexBuffer.PositionKind
  31366. * - BABYLON.VertexBuffer.UVKind
  31367. * - BABYLON.VertexBuffer.UV2Kind
  31368. * - BABYLON.VertexBuffer.UV3Kind
  31369. * - BABYLON.VertexBuffer.UV4Kind
  31370. * - BABYLON.VertexBuffer.UV5Kind
  31371. * - BABYLON.VertexBuffer.UV6Kind
  31372. * - BABYLON.VertexBuffer.ColorKind
  31373. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31374. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31375. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31376. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31377. */
  31378. Mesh.prototype.getVertexBuffer = function (kind) {
  31379. if (!this._geometry) {
  31380. return null;
  31381. }
  31382. return this._geometry.getVertexBuffer(kind);
  31383. };
  31384. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31385. if (!this._geometry) {
  31386. if (this._delayInfo) {
  31387. return this._delayInfo.indexOf(kind) !== -1;
  31388. }
  31389. return false;
  31390. }
  31391. return this._geometry.isVerticesDataPresent(kind);
  31392. };
  31393. /**
  31394. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31395. * Possible `kind` values :
  31396. * - BABYLON.VertexBuffer.PositionKind
  31397. * - BABYLON.VertexBuffer.UVKind
  31398. * - BABYLON.VertexBuffer.UV2Kind
  31399. * - BABYLON.VertexBuffer.UV3Kind
  31400. * - BABYLON.VertexBuffer.UV4Kind
  31401. * - BABYLON.VertexBuffer.UV5Kind
  31402. * - BABYLON.VertexBuffer.UV6Kind
  31403. * - BABYLON.VertexBuffer.ColorKind
  31404. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31405. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31406. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31407. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31408. */
  31409. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31410. if (!this._geometry) {
  31411. if (this._delayInfo) {
  31412. return this._delayInfo.indexOf(kind) !== -1;
  31413. }
  31414. return false;
  31415. }
  31416. return this._geometry.isVertexBufferUpdatable(kind);
  31417. };
  31418. /**
  31419. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31420. * Possible `kind` values :
  31421. * - BABYLON.VertexBuffer.PositionKind
  31422. * - BABYLON.VertexBuffer.UVKind
  31423. * - BABYLON.VertexBuffer.UV2Kind
  31424. * - BABYLON.VertexBuffer.UV3Kind
  31425. * - BABYLON.VertexBuffer.UV4Kind
  31426. * - BABYLON.VertexBuffer.UV5Kind
  31427. * - BABYLON.VertexBuffer.UV6Kind
  31428. * - BABYLON.VertexBuffer.ColorKind
  31429. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31430. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31431. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31432. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31433. */
  31434. Mesh.prototype.getVerticesDataKinds = function () {
  31435. if (!this._geometry) {
  31436. var result = new Array();
  31437. if (this._delayInfo) {
  31438. this._delayInfo.forEach(function (kind, index, array) {
  31439. result.push(kind);
  31440. });
  31441. }
  31442. return result;
  31443. }
  31444. return this._geometry.getVerticesDataKinds();
  31445. };
  31446. /**
  31447. * Returns a positive integer : the total number of indices in this mesh geometry.
  31448. * Returns zero if the mesh has no geometry.
  31449. */
  31450. Mesh.prototype.getTotalIndices = function () {
  31451. if (!this._geometry) {
  31452. return 0;
  31453. }
  31454. return this._geometry.getTotalIndices();
  31455. };
  31456. /**
  31457. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31458. * 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.
  31459. * Returns an empty array if the mesh has no geometry.
  31460. */
  31461. Mesh.prototype.getIndices = function (copyWhenShared) {
  31462. if (!this._geometry) {
  31463. return [];
  31464. }
  31465. return this._geometry.getIndices(copyWhenShared);
  31466. };
  31467. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31468. get: function () {
  31469. return this._masterMesh !== null && this._masterMesh !== undefined;
  31470. },
  31471. enumerable: true,
  31472. configurable: true
  31473. });
  31474. /**
  31475. * Determine if the current mesh is ready to be rendered
  31476. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31477. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31478. * @returns true if all associated assets are ready (material, textures, shaders)
  31479. */
  31480. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31481. if (completeCheck === void 0) { completeCheck = false; }
  31482. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31483. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31484. return false;
  31485. }
  31486. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31487. return false;
  31488. }
  31489. if (!this.subMeshes || this.subMeshes.length === 0) {
  31490. return true;
  31491. }
  31492. if (!completeCheck) {
  31493. return true;
  31494. }
  31495. var engine = this.getEngine();
  31496. var scene = this.getScene();
  31497. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31498. this.computeWorldMatrix();
  31499. var mat = this.material || scene.defaultMaterial;
  31500. if (mat) {
  31501. if (mat.storeEffectOnSubMeshes) {
  31502. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31503. var subMesh = _a[_i];
  31504. var effectiveMaterial = subMesh.getMaterial();
  31505. if (effectiveMaterial) {
  31506. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31507. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31508. return false;
  31509. }
  31510. }
  31511. else {
  31512. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31513. return false;
  31514. }
  31515. }
  31516. }
  31517. }
  31518. }
  31519. else {
  31520. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31521. return false;
  31522. }
  31523. }
  31524. }
  31525. // Shadows
  31526. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31527. var light = _c[_b];
  31528. var generator = light.getShadowGenerator();
  31529. if (generator) {
  31530. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31531. var subMesh = _e[_d];
  31532. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31533. return false;
  31534. }
  31535. }
  31536. }
  31537. }
  31538. // LOD
  31539. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31540. var lod = _g[_f];
  31541. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31542. return false;
  31543. }
  31544. }
  31545. return true;
  31546. };
  31547. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31548. /**
  31549. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31550. * This property is pertinent only for updatable parametric shapes.
  31551. */
  31552. get: function () {
  31553. return this._areNormalsFrozen;
  31554. },
  31555. enumerable: true,
  31556. configurable: true
  31557. });
  31558. /**
  31559. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31560. * It has no effect at all on other shapes.
  31561. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31562. * Returns the Mesh.
  31563. */
  31564. Mesh.prototype.freezeNormals = function () {
  31565. this._areNormalsFrozen = true;
  31566. return this;
  31567. };
  31568. /**
  31569. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31570. * It has no effect at all on other shapes.
  31571. * It reactivates the mesh normals computation if it was previously frozen.
  31572. * Returns the Mesh.
  31573. */
  31574. Mesh.prototype.unfreezeNormals = function () {
  31575. this._areNormalsFrozen = false;
  31576. return this;
  31577. };
  31578. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31579. /**
  31580. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31581. */
  31582. set: function (count) {
  31583. this._overridenInstanceCount = count;
  31584. },
  31585. enumerable: true,
  31586. configurable: true
  31587. });
  31588. // Methods
  31589. Mesh.prototype._preActivate = function () {
  31590. var sceneRenderId = this.getScene().getRenderId();
  31591. if (this._preActivateId === sceneRenderId) {
  31592. return this;
  31593. }
  31594. this._preActivateId = sceneRenderId;
  31595. this._visibleInstances = null;
  31596. return this;
  31597. };
  31598. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31599. if (this._visibleInstances) {
  31600. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31601. }
  31602. return this;
  31603. };
  31604. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31605. if (!this._visibleInstances) {
  31606. this._visibleInstances = {};
  31607. this._visibleInstances.defaultRenderId = renderId;
  31608. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31609. }
  31610. if (!this._visibleInstances[renderId]) {
  31611. this._visibleInstances[renderId] = new Array();
  31612. }
  31613. this._visibleInstances[renderId].push(instance);
  31614. return this;
  31615. };
  31616. /**
  31617. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31618. * This means the mesh underlying bounding box and sphere are recomputed.
  31619. * Returns the Mesh.
  31620. */
  31621. Mesh.prototype.refreshBoundingInfo = function () {
  31622. return this._refreshBoundingInfo(false);
  31623. };
  31624. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31625. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31626. return this;
  31627. }
  31628. var data = this._getPositionData(applySkeleton);
  31629. if (data) {
  31630. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31631. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31632. }
  31633. if (this.subMeshes) {
  31634. for (var index = 0; index < this.subMeshes.length; index++) {
  31635. this.subMeshes[index].refreshBoundingInfo();
  31636. }
  31637. }
  31638. this._updateBoundingInfo();
  31639. return this;
  31640. };
  31641. Mesh.prototype._getPositionData = function (applySkeleton) {
  31642. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31643. if (data && applySkeleton && this.skeleton) {
  31644. data = BABYLON.Tools.Slice(data);
  31645. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31646. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31647. if (matricesWeightsData && matricesIndicesData) {
  31648. var needExtras = this.numBoneInfluencers > 4;
  31649. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31650. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31651. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31652. var tempVector = BABYLON.Tmp.Vector3[0];
  31653. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31654. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31655. var matWeightIdx = 0;
  31656. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31657. finalMatrix.reset();
  31658. var inf;
  31659. var weight;
  31660. for (inf = 0; inf < 4; inf++) {
  31661. weight = matricesWeightsData[matWeightIdx + inf];
  31662. if (weight <= 0)
  31663. break;
  31664. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31665. finalMatrix.addToSelf(tempMatrix);
  31666. }
  31667. if (needExtras) {
  31668. for (inf = 0; inf < 4; inf++) {
  31669. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31670. if (weight <= 0)
  31671. break;
  31672. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31673. finalMatrix.addToSelf(tempMatrix);
  31674. }
  31675. }
  31676. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31677. tempVector.toArray(data, index);
  31678. }
  31679. }
  31680. }
  31681. return data;
  31682. };
  31683. Mesh.prototype._createGlobalSubMesh = function (force) {
  31684. var totalVertices = this.getTotalVertices();
  31685. if (!totalVertices || !this.getIndices()) {
  31686. return null;
  31687. }
  31688. // Check if we need to recreate the submeshes
  31689. if (this.subMeshes && this.subMeshes.length > 0) {
  31690. var ib = this.getIndices();
  31691. if (!ib) {
  31692. return null;
  31693. }
  31694. var totalIndices = ib.length;
  31695. var needToRecreate = false;
  31696. if (force) {
  31697. needToRecreate = true;
  31698. }
  31699. else {
  31700. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31701. var submesh = _a[_i];
  31702. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31703. needToRecreate = true;
  31704. break;
  31705. }
  31706. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31707. needToRecreate = true;
  31708. break;
  31709. }
  31710. }
  31711. }
  31712. if (!needToRecreate) {
  31713. return this.subMeshes[0];
  31714. }
  31715. }
  31716. this.releaseSubMeshes();
  31717. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31718. };
  31719. Mesh.prototype.subdivide = function (count) {
  31720. if (count < 1) {
  31721. return;
  31722. }
  31723. var totalIndices = this.getTotalIndices();
  31724. var subdivisionSize = (totalIndices / count) | 0;
  31725. var offset = 0;
  31726. // Ensure that subdivisionSize is a multiple of 3
  31727. while (subdivisionSize % 3 !== 0) {
  31728. subdivisionSize++;
  31729. }
  31730. this.releaseSubMeshes();
  31731. for (var index = 0; index < count; index++) {
  31732. if (offset >= totalIndices) {
  31733. break;
  31734. }
  31735. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31736. offset += subdivisionSize;
  31737. }
  31738. this.synchronizeInstances();
  31739. };
  31740. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31741. if (updatable === void 0) { updatable = false; }
  31742. if (!this._geometry) {
  31743. var vertexData = new BABYLON.VertexData();
  31744. vertexData.set(data, kind);
  31745. var scene = this.getScene();
  31746. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31747. }
  31748. else {
  31749. this._geometry.setVerticesData(kind, data, updatable, stride);
  31750. }
  31751. return this;
  31752. };
  31753. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31754. if (updatable === void 0) { updatable = true; }
  31755. var vb = this.getVertexBuffer(kind);
  31756. if (!vb || vb.isUpdatable() === updatable) {
  31757. return;
  31758. }
  31759. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31760. };
  31761. /**
  31762. * Sets the mesh VertexBuffer.
  31763. * Returns the Mesh.
  31764. */
  31765. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31766. if (!this._geometry) {
  31767. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31768. }
  31769. this._geometry.setVerticesBuffer(buffer);
  31770. return this;
  31771. };
  31772. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31773. if (!this._geometry) {
  31774. return this;
  31775. }
  31776. if (!makeItUnique) {
  31777. this._geometry.updateVerticesData(kind, data, updateExtends);
  31778. }
  31779. else {
  31780. this.makeGeometryUnique();
  31781. this.updateVerticesData(kind, data, updateExtends, false);
  31782. }
  31783. return this;
  31784. };
  31785. /**
  31786. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31787. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31788. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31789. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31790. * Returns the Mesh.
  31791. */
  31792. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31793. if (computeNormals === void 0) { computeNormals = true; }
  31794. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31795. if (!positions) {
  31796. return this;
  31797. }
  31798. positionFunction(positions);
  31799. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31800. if (computeNormals) {
  31801. var indices = this.getIndices();
  31802. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31803. if (!normals) {
  31804. return this;
  31805. }
  31806. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31807. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31808. }
  31809. return this;
  31810. };
  31811. /**
  31812. * Creates a un-shared specific occurence of the geometry for the mesh.
  31813. * Returns the Mesh.
  31814. */
  31815. Mesh.prototype.makeGeometryUnique = function () {
  31816. if (!this._geometry) {
  31817. return this;
  31818. }
  31819. var oldGeometry = this._geometry;
  31820. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31821. oldGeometry.releaseForMesh(this, true);
  31822. geometry.applyToMesh(this);
  31823. return this;
  31824. };
  31825. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31826. if (totalVertices === void 0) { totalVertices = null; }
  31827. if (updatable === void 0) { updatable = false; }
  31828. if (!this._geometry) {
  31829. var vertexData = new BABYLON.VertexData();
  31830. vertexData.indices = indices;
  31831. var scene = this.getScene();
  31832. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31833. }
  31834. else {
  31835. this._geometry.setIndices(indices, totalVertices, updatable);
  31836. }
  31837. return this;
  31838. };
  31839. /**
  31840. * Update the current index buffer
  31841. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31842. * Returns the Mesh.
  31843. */
  31844. Mesh.prototype.updateIndices = function (indices, offset) {
  31845. if (!this._geometry) {
  31846. return this;
  31847. }
  31848. this._geometry.updateIndices(indices, offset);
  31849. return this;
  31850. };
  31851. /**
  31852. * Invert the geometry to move from a right handed system to a left handed one.
  31853. * Returns the Mesh.
  31854. */
  31855. Mesh.prototype.toLeftHanded = function () {
  31856. if (!this._geometry) {
  31857. return this;
  31858. }
  31859. this._geometry.toLeftHanded();
  31860. return this;
  31861. };
  31862. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31863. if (!this._geometry) {
  31864. return this;
  31865. }
  31866. var engine = this.getScene().getEngine();
  31867. // Wireframe
  31868. var indexToBind;
  31869. if (this._unIndexed) {
  31870. indexToBind = null;
  31871. }
  31872. else {
  31873. switch (fillMode) {
  31874. case BABYLON.Material.PointFillMode:
  31875. indexToBind = null;
  31876. break;
  31877. case BABYLON.Material.WireFrameFillMode:
  31878. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31879. break;
  31880. default:
  31881. case BABYLON.Material.TriangleFillMode:
  31882. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31883. break;
  31884. }
  31885. }
  31886. // VBOs
  31887. this._geometry._bind(effect, indexToBind);
  31888. return this;
  31889. };
  31890. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31891. if (alternate === void 0) { alternate = false; }
  31892. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31893. return this;
  31894. }
  31895. this.onBeforeDrawObservable.notifyObservers(this);
  31896. var scene = this.getScene();
  31897. var engine = scene.getEngine();
  31898. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31899. // or triangles as points
  31900. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31901. }
  31902. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31903. // Triangles as wireframe
  31904. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31905. }
  31906. else {
  31907. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31908. }
  31909. if (scene._isAlternateRenderingEnabled && !alternate) {
  31910. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31911. if (!effect || !scene.activeCamera) {
  31912. return this;
  31913. }
  31914. scene._switchToAlternateCameraConfiguration(true);
  31915. this._effectiveMaterial.bindView(effect);
  31916. this._effectiveMaterial.bindViewProjection(effect);
  31917. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31918. this._draw(subMesh, fillMode, instancesCount, true);
  31919. engine.setViewport(scene.activeCamera.viewport);
  31920. scene._switchToAlternateCameraConfiguration(false);
  31921. this._effectiveMaterial.bindView(effect);
  31922. this._effectiveMaterial.bindViewProjection(effect);
  31923. }
  31924. return this;
  31925. };
  31926. /**
  31927. * Registers for this mesh a javascript function called just before the rendering process.
  31928. * This function is passed the current mesh.
  31929. * Return the Mesh.
  31930. */
  31931. Mesh.prototype.registerBeforeRender = function (func) {
  31932. this.onBeforeRenderObservable.add(func);
  31933. return this;
  31934. };
  31935. /**
  31936. * Disposes a previously registered javascript function called before the rendering.
  31937. * This function is passed the current mesh.
  31938. * Returns the Mesh.
  31939. */
  31940. Mesh.prototype.unregisterBeforeRender = function (func) {
  31941. this.onBeforeRenderObservable.removeCallback(func);
  31942. return this;
  31943. };
  31944. /**
  31945. * Registers for this mesh a javascript function called just after the rendering is complete.
  31946. * This function is passed the current mesh.
  31947. * Returns the Mesh.
  31948. */
  31949. Mesh.prototype.registerAfterRender = function (func) {
  31950. this.onAfterRenderObservable.add(func);
  31951. return this;
  31952. };
  31953. /**
  31954. * Disposes a previously registered javascript function called after the rendering.
  31955. * This function is passed the current mesh.
  31956. * Return the Mesh.
  31957. */
  31958. Mesh.prototype.unregisterAfterRender = function (func) {
  31959. this.onAfterRenderObservable.removeCallback(func);
  31960. return this;
  31961. };
  31962. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31963. var scene = this.getScene();
  31964. this._batchCache.mustReturn = false;
  31965. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31966. this._batchCache.visibleInstances[subMeshId] = null;
  31967. if (this._visibleInstances) {
  31968. var currentRenderId = scene.getRenderId();
  31969. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31970. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31971. var selfRenderId = this._renderId;
  31972. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31973. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31974. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31975. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31976. }
  31977. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31978. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31979. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31980. this._batchCache.mustReturn = true;
  31981. return this._batchCache;
  31982. }
  31983. if (currentRenderId !== selfRenderId) {
  31984. this._batchCache.renderSelf[subMeshId] = false;
  31985. }
  31986. }
  31987. this._renderIdForInstances[subMeshId] = currentRenderId;
  31988. }
  31989. return this._batchCache;
  31990. };
  31991. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31992. var visibleInstances = batch.visibleInstances[subMesh._id];
  31993. if (!visibleInstances) {
  31994. return this;
  31995. }
  31996. var matricesCount = visibleInstances.length + 1;
  31997. var bufferSize = matricesCount * 16 * 4;
  31998. var currentInstancesBufferSize = this._instancesBufferSize;
  31999. var instancesBuffer = this._instancesBuffer;
  32000. while (this._instancesBufferSize < bufferSize) {
  32001. this._instancesBufferSize *= 2;
  32002. }
  32003. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32004. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32005. }
  32006. var offset = 0;
  32007. var instancesCount = 0;
  32008. var world = this.getWorldMatrix();
  32009. if (batch.renderSelf[subMesh._id]) {
  32010. world.copyToArray(this._instancesData, offset);
  32011. offset += 16;
  32012. instancesCount++;
  32013. }
  32014. if (visibleInstances) {
  32015. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32016. var instance = visibleInstances[instanceIndex];
  32017. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32018. offset += 16;
  32019. instancesCount++;
  32020. }
  32021. }
  32022. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32023. if (instancesBuffer) {
  32024. instancesBuffer.dispose();
  32025. }
  32026. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32027. this._instancesBuffer = instancesBuffer;
  32028. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32029. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32030. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32031. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32032. }
  32033. else {
  32034. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32035. }
  32036. this._bind(subMesh, effect, fillMode);
  32037. this._draw(subMesh, fillMode, instancesCount);
  32038. engine.unbindInstanceAttributes();
  32039. return this;
  32040. };
  32041. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32042. var scene = this.getScene();
  32043. var engine = scene.getEngine();
  32044. if (hardwareInstancedRendering) {
  32045. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32046. }
  32047. else {
  32048. if (batch.renderSelf[subMesh._id]) {
  32049. // Draw
  32050. if (onBeforeDraw) {
  32051. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32052. }
  32053. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32054. }
  32055. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32056. if (visibleInstancesForSubMesh) {
  32057. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32058. var instance = visibleInstancesForSubMesh[instanceIndex];
  32059. // World
  32060. var world = instance.getWorldMatrix();
  32061. if (onBeforeDraw) {
  32062. onBeforeDraw(true, world, effectiveMaterial);
  32063. }
  32064. // Draw
  32065. this._draw(subMesh, fillMode);
  32066. }
  32067. }
  32068. }
  32069. return this;
  32070. };
  32071. /**
  32072. * Triggers the draw call for the mesh.
  32073. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32074. * Returns the Mesh.
  32075. */
  32076. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32077. this._checkOcclusionQuery();
  32078. if (this._isOccluded) {
  32079. return this;
  32080. }
  32081. var scene = this.getScene();
  32082. // Managing instances
  32083. var batch = this._getInstancesRenderList(subMesh._id);
  32084. if (batch.mustReturn) {
  32085. return this;
  32086. }
  32087. // Checking geometry state
  32088. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32089. return this;
  32090. }
  32091. this.onBeforeRenderObservable.notifyObservers(this);
  32092. var engine = scene.getEngine();
  32093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32094. // Material
  32095. var material = subMesh.getMaterial();
  32096. if (!material) {
  32097. return this;
  32098. }
  32099. this._effectiveMaterial = material;
  32100. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32101. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32102. return this;
  32103. }
  32104. }
  32105. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32106. return this;
  32107. }
  32108. // Alpha mode
  32109. if (enableAlphaMode) {
  32110. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32111. }
  32112. // Outline - step 1
  32113. var savedDepthWrite = engine.getDepthWrite();
  32114. if (this.renderOutline) {
  32115. engine.setDepthWrite(false);
  32116. scene.getOutlineRenderer().render(subMesh, batch);
  32117. engine.setDepthWrite(savedDepthWrite);
  32118. }
  32119. var effect;
  32120. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32121. effect = subMesh.effect;
  32122. }
  32123. else {
  32124. effect = this._effectiveMaterial.getEffect();
  32125. }
  32126. if (!effect) {
  32127. return this;
  32128. }
  32129. var sideOrientation = this.overrideMaterialSideOrientation;
  32130. if (sideOrientation == null) {
  32131. sideOrientation = this._effectiveMaterial.sideOrientation;
  32132. if (this._getWorldMatrixDeterminant() < 0) {
  32133. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32134. }
  32135. }
  32136. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32137. if (this._effectiveMaterial.forceDepthWrite) {
  32138. engine.setDepthWrite(true);
  32139. }
  32140. // Bind
  32141. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32142. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32143. this._bind(subMesh, effect, fillMode);
  32144. }
  32145. var world = this.getWorldMatrix();
  32146. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32147. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32148. }
  32149. else {
  32150. this._effectiveMaterial.bind(world, this);
  32151. }
  32152. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32153. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32154. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32155. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32156. }
  32157. // Draw
  32158. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32159. // Unbind
  32160. this._effectiveMaterial.unbind();
  32161. // Outline - step 2
  32162. if (this.renderOutline && savedDepthWrite) {
  32163. engine.setDepthWrite(true);
  32164. engine.setColorWrite(false);
  32165. scene.getOutlineRenderer().render(subMesh, batch);
  32166. engine.setColorWrite(true);
  32167. }
  32168. // Overlay
  32169. if (this.renderOverlay) {
  32170. var currentMode = engine.getAlphaMode();
  32171. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32172. scene.getOutlineRenderer().render(subMesh, batch, true);
  32173. engine.setAlphaMode(currentMode);
  32174. }
  32175. this.onAfterRenderObservable.notifyObservers(this);
  32176. return this;
  32177. };
  32178. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32179. if (isInstance && effectiveMaterial) {
  32180. effectiveMaterial.bindOnlyWorldMatrix(world);
  32181. }
  32182. };
  32183. /**
  32184. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32185. */
  32186. Mesh.prototype.getEmittedParticleSystems = function () {
  32187. var results = new Array();
  32188. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32189. var particleSystem = this.getScene().particleSystems[index];
  32190. if (particleSystem.emitter === this) {
  32191. results.push(particleSystem);
  32192. }
  32193. }
  32194. return results;
  32195. };
  32196. /**
  32197. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32198. */
  32199. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32200. var results = new Array();
  32201. var descendants = this.getDescendants();
  32202. descendants.push(this);
  32203. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32204. var particleSystem = this.getScene().particleSystems[index];
  32205. var emitter = particleSystem.emitter;
  32206. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32207. results.push(particleSystem);
  32208. }
  32209. }
  32210. return results;
  32211. };
  32212. Mesh.prototype._checkDelayState = function () {
  32213. var scene = this.getScene();
  32214. if (this._geometry) {
  32215. this._geometry.load(scene);
  32216. }
  32217. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32218. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32219. this._queueLoad(scene);
  32220. }
  32221. return this;
  32222. };
  32223. Mesh.prototype._queueLoad = function (scene) {
  32224. var _this = this;
  32225. scene._addPendingData(this);
  32226. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32227. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32228. if (data instanceof ArrayBuffer) {
  32229. _this._delayLoadingFunction(data, _this);
  32230. }
  32231. else {
  32232. _this._delayLoadingFunction(JSON.parse(data), _this);
  32233. }
  32234. _this.instances.forEach(function (instance) {
  32235. instance._syncSubMeshes();
  32236. });
  32237. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32238. scene._removePendingData(_this);
  32239. }, function () { }, scene.database, getBinaryData);
  32240. return this;
  32241. };
  32242. /**
  32243. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32244. */
  32245. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32246. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32247. return false;
  32248. }
  32249. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32250. return false;
  32251. }
  32252. this._checkDelayState();
  32253. return true;
  32254. };
  32255. /**
  32256. * Sets the mesh material by the material or multiMaterial `id` property.
  32257. * The material `id` is a string identifying the material or the multiMaterial.
  32258. * This method returns the Mesh.
  32259. */
  32260. Mesh.prototype.setMaterialByID = function (id) {
  32261. var materials = this.getScene().materials;
  32262. var index;
  32263. for (index = materials.length - 1; index > -1; index--) {
  32264. if (materials[index].id === id) {
  32265. this.material = materials[index];
  32266. return this;
  32267. }
  32268. }
  32269. // Multi
  32270. var multiMaterials = this.getScene().multiMaterials;
  32271. for (index = multiMaterials.length - 1; index > -1; index--) {
  32272. if (multiMaterials[index].id === id) {
  32273. this.material = multiMaterials[index];
  32274. return this;
  32275. }
  32276. }
  32277. return this;
  32278. };
  32279. /**
  32280. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32281. */
  32282. Mesh.prototype.getAnimatables = function () {
  32283. var results = new Array();
  32284. if (this.material) {
  32285. results.push(this.material);
  32286. }
  32287. if (this.skeleton) {
  32288. results.push(this.skeleton);
  32289. }
  32290. return results;
  32291. };
  32292. /**
  32293. * Modifies the mesh geometry according to the passed transformation matrix.
  32294. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32295. * The mesh normals are modified accordingly the same transformation.
  32296. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32297. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32298. * Returns the Mesh.
  32299. */
  32300. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32301. // Position
  32302. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32303. return this;
  32304. }
  32305. var submeshes = this.subMeshes.splice(0);
  32306. this._resetPointsArrayCache();
  32307. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32308. var temp = new Array();
  32309. var index;
  32310. for (index = 0; index < data.length; index += 3) {
  32311. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32312. }
  32313. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32314. // Normals
  32315. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32316. return this;
  32317. }
  32318. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32319. temp = [];
  32320. for (index = 0; index < data.length; index += 3) {
  32321. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32322. }
  32323. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32324. // flip faces?
  32325. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32326. this.flipFaces();
  32327. }
  32328. // Restore submeshes
  32329. this.releaseSubMeshes();
  32330. this.subMeshes = submeshes;
  32331. return this;
  32332. };
  32333. /**
  32334. * Modifies the mesh geometry according to its own current World Matrix.
  32335. * The mesh World Matrix is then reset.
  32336. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32337. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32338. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32339. * Returns the Mesh.
  32340. */
  32341. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32342. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32343. this.scaling.copyFromFloats(1, 1, 1);
  32344. this.position.copyFromFloats(0, 0, 0);
  32345. this.rotation.copyFromFloats(0, 0, 0);
  32346. //only if quaternion is already set
  32347. if (this.rotationQuaternion) {
  32348. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32349. }
  32350. this._worldMatrix = BABYLON.Matrix.Identity();
  32351. return this;
  32352. };
  32353. Object.defineProperty(Mesh.prototype, "_positions", {
  32354. // Cache
  32355. get: function () {
  32356. if (this._geometry) {
  32357. return this._geometry._positions;
  32358. }
  32359. return null;
  32360. },
  32361. enumerable: true,
  32362. configurable: true
  32363. });
  32364. Mesh.prototype._resetPointsArrayCache = function () {
  32365. if (this._geometry) {
  32366. this._geometry._resetPointsArrayCache();
  32367. }
  32368. return this;
  32369. };
  32370. Mesh.prototype._generatePointsArray = function () {
  32371. if (this._geometry) {
  32372. return this._geometry._generatePointsArray();
  32373. }
  32374. return false;
  32375. };
  32376. /**
  32377. * Returns a new Mesh object generated from the current mesh properties.
  32378. * This method must not get confused with createInstance().
  32379. * The parameter `name` is a string, the name given to the new mesh.
  32380. * The optional parameter `newParent` can be any Node object (default `null`).
  32381. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32382. * 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.
  32383. */
  32384. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32385. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32386. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32387. };
  32388. /**
  32389. * Releases resources associated with this mesh.
  32390. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32391. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32392. */
  32393. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32394. var _this = this;
  32395. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32396. this.morphTargetManager = null;
  32397. if (this._geometry) {
  32398. this._geometry.releaseForMesh(this, true);
  32399. }
  32400. // Sources
  32401. var meshes = this.getScene().meshes;
  32402. meshes.forEach(function (abstractMesh) {
  32403. var mesh = abstractMesh;
  32404. if (mesh._source && mesh._source === _this) {
  32405. mesh._source = null;
  32406. }
  32407. });
  32408. this._source = null;
  32409. // Instances
  32410. if (this._instancesBuffer) {
  32411. this._instancesBuffer.dispose();
  32412. this._instancesBuffer = null;
  32413. }
  32414. while (this.instances.length) {
  32415. this.instances[0].dispose();
  32416. }
  32417. // Effect layers.
  32418. var effectLayers = this.getScene().effectLayers;
  32419. for (var i = 0; i < effectLayers.length; i++) {
  32420. var effectLayer = effectLayers[i];
  32421. if (effectLayer) {
  32422. effectLayer._disposeMesh(this);
  32423. }
  32424. }
  32425. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32426. };
  32427. /**
  32428. * Modifies the mesh geometry according to a displacement map.
  32429. * 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.
  32430. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32431. * This method returns nothing.
  32432. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32433. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32434. * 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.
  32435. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32436. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32437. *
  32438. * Returns the Mesh.
  32439. */
  32440. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32441. var _this = this;
  32442. var scene = this.getScene();
  32443. var onload = function (img) {
  32444. // Getting height map data
  32445. var canvas = document.createElement("canvas");
  32446. var context = canvas.getContext("2d");
  32447. var heightMapWidth = img.width;
  32448. var heightMapHeight = img.height;
  32449. canvas.width = heightMapWidth;
  32450. canvas.height = heightMapHeight;
  32451. context.drawImage(img, 0, 0);
  32452. // Create VertexData from map data
  32453. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32454. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32455. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32456. //execute success callback, if set
  32457. if (onSuccess) {
  32458. onSuccess(_this);
  32459. }
  32460. };
  32461. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32462. return this;
  32463. };
  32464. /**
  32465. * Modifies the mesh geometry according to a displacementMap buffer.
  32466. * 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.
  32467. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32468. * This method returns nothing.
  32469. * 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.
  32470. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32471. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32472. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32473. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32474. *
  32475. * Returns the Mesh.
  32476. */
  32477. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32478. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32479. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32480. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32481. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32482. return this;
  32483. }
  32484. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32485. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32486. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32487. var position = BABYLON.Vector3.Zero();
  32488. var normal = BABYLON.Vector3.Zero();
  32489. var uv = BABYLON.Vector2.Zero();
  32490. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32491. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32492. for (var index = 0; index < positions.length; index += 3) {
  32493. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32494. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32495. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32496. // Compute height
  32497. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32498. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32499. var pos = (u + v * heightMapWidth) * 4;
  32500. var r = buffer[pos] / 255.0;
  32501. var g = buffer[pos + 1] / 255.0;
  32502. var b = buffer[pos + 2] / 255.0;
  32503. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32504. normal.normalize();
  32505. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32506. position = position.add(normal);
  32507. position.toArray(positions, index);
  32508. }
  32509. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32510. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32511. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32512. return this;
  32513. };
  32514. /**
  32515. * Modify the mesh to get a flat shading rendering.
  32516. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32517. * This method returns the Mesh.
  32518. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32519. */
  32520. Mesh.prototype.convertToFlatShadedMesh = function () {
  32521. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32522. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32523. var kinds = this.getVerticesDataKinds();
  32524. var vbs = {};
  32525. var data = {};
  32526. var newdata = {};
  32527. var updatableNormals = false;
  32528. var kindIndex;
  32529. var kind;
  32530. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32531. kind = kinds[kindIndex];
  32532. var vertexBuffer = this.getVertexBuffer(kind);
  32533. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32534. updatableNormals = vertexBuffer.isUpdatable();
  32535. kinds.splice(kindIndex, 1);
  32536. kindIndex--;
  32537. continue;
  32538. }
  32539. vbs[kind] = vertexBuffer;
  32540. data[kind] = vbs[kind].getData();
  32541. newdata[kind] = [];
  32542. }
  32543. // Save previous submeshes
  32544. var previousSubmeshes = this.subMeshes.slice(0);
  32545. var indices = this.getIndices();
  32546. var totalIndices = this.getTotalIndices();
  32547. // Generating unique vertices per face
  32548. var index;
  32549. for (index = 0; index < totalIndices; index++) {
  32550. var vertexIndex = indices[index];
  32551. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32552. kind = kinds[kindIndex];
  32553. var stride = vbs[kind].getStrideSize();
  32554. for (var offset = 0; offset < stride; offset++) {
  32555. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32556. }
  32557. }
  32558. }
  32559. // Updating faces & normal
  32560. var normals = [];
  32561. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32562. for (index = 0; index < totalIndices; index += 3) {
  32563. indices[index] = index;
  32564. indices[index + 1] = index + 1;
  32565. indices[index + 2] = index + 2;
  32566. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32567. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32568. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32569. var p1p2 = p1.subtract(p2);
  32570. var p3p2 = p3.subtract(p2);
  32571. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32572. // Store same normals for every vertex
  32573. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32574. normals.push(normal.x);
  32575. normals.push(normal.y);
  32576. normals.push(normal.z);
  32577. }
  32578. }
  32579. this.setIndices(indices);
  32580. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32581. // Updating vertex buffers
  32582. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32583. kind = kinds[kindIndex];
  32584. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32585. }
  32586. // Updating submeshes
  32587. this.releaseSubMeshes();
  32588. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32589. var previousOne = previousSubmeshes[submeshIndex];
  32590. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32591. }
  32592. this.synchronizeInstances();
  32593. return this;
  32594. };
  32595. /**
  32596. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32597. * In other words, more vertices, no more indices and a single bigger VBO.
  32598. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32599. * Returns the Mesh.
  32600. */
  32601. Mesh.prototype.convertToUnIndexedMesh = function () {
  32602. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32603. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32604. var kinds = this.getVerticesDataKinds();
  32605. var vbs = {};
  32606. var data = {};
  32607. var newdata = {};
  32608. var kindIndex;
  32609. var kind;
  32610. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32611. kind = kinds[kindIndex];
  32612. var vertexBuffer = this.getVertexBuffer(kind);
  32613. vbs[kind] = vertexBuffer;
  32614. data[kind] = vbs[kind].getData();
  32615. newdata[kind] = [];
  32616. }
  32617. // Save previous submeshes
  32618. var previousSubmeshes = this.subMeshes.slice(0);
  32619. var indices = this.getIndices();
  32620. var totalIndices = this.getTotalIndices();
  32621. // Generating unique vertices per face
  32622. var index;
  32623. for (index = 0; index < totalIndices; index++) {
  32624. var vertexIndex = indices[index];
  32625. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32626. kind = kinds[kindIndex];
  32627. var stride = vbs[kind].getStrideSize();
  32628. for (var offset = 0; offset < stride; offset++) {
  32629. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32630. }
  32631. }
  32632. }
  32633. // Updating indices
  32634. for (index = 0; index < totalIndices; index += 3) {
  32635. indices[index] = index;
  32636. indices[index + 1] = index + 1;
  32637. indices[index + 2] = index + 2;
  32638. }
  32639. this.setIndices(indices);
  32640. // Updating vertex buffers
  32641. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32642. kind = kinds[kindIndex];
  32643. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32644. }
  32645. // Updating submeshes
  32646. this.releaseSubMeshes();
  32647. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32648. var previousOne = previousSubmeshes[submeshIndex];
  32649. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32650. }
  32651. this._unIndexed = true;
  32652. this.synchronizeInstances();
  32653. return this;
  32654. };
  32655. /**
  32656. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32657. * This method returns the Mesh.
  32658. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32659. */
  32660. Mesh.prototype.flipFaces = function (flipNormals) {
  32661. if (flipNormals === void 0) { flipNormals = false; }
  32662. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32663. var i;
  32664. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32665. for (i = 0; i < vertex_data.normals.length; i++) {
  32666. vertex_data.normals[i] *= -1;
  32667. }
  32668. }
  32669. if (vertex_data.indices) {
  32670. var temp;
  32671. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32672. // reassign indices
  32673. temp = vertex_data.indices[i + 1];
  32674. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32675. vertex_data.indices[i + 2] = temp;
  32676. }
  32677. }
  32678. vertex_data.applyToMesh(this);
  32679. return this;
  32680. };
  32681. // Instances
  32682. /**
  32683. * Creates a new InstancedMesh object from the mesh model.
  32684. * An instance shares the same properties and the same material than its model.
  32685. * Only these properties of each instance can then be set individually :
  32686. * - position
  32687. * - rotation
  32688. * - rotationQuaternion
  32689. * - setPivotMatrix
  32690. * - scaling
  32691. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32692. * Warning : this method is not supported for Line mesh and LineSystem
  32693. */
  32694. Mesh.prototype.createInstance = function (name) {
  32695. return new BABYLON.InstancedMesh(name, this);
  32696. };
  32697. /**
  32698. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32699. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32700. * This method returns the Mesh.
  32701. */
  32702. Mesh.prototype.synchronizeInstances = function () {
  32703. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32704. var instance = this.instances[instanceIndex];
  32705. instance._syncSubMeshes();
  32706. }
  32707. return this;
  32708. };
  32709. /**
  32710. * Simplify the mesh according to the given array of settings.
  32711. * Function will return immediately and will simplify async. It returns the Mesh.
  32712. * @param settings a collection of simplification settings.
  32713. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32714. * @param type the type of simplification to run.
  32715. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32716. */
  32717. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32718. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32719. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32720. this.getScene().simplificationQueue.addTask({
  32721. settings: settings,
  32722. parallelProcessing: parallelProcessing,
  32723. mesh: this,
  32724. simplificationType: simplificationType,
  32725. successCallback: successCallback
  32726. });
  32727. return this;
  32728. };
  32729. /**
  32730. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32731. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32732. * This should be used together with the simplification to avoid disappearing triangles.
  32733. * Returns the Mesh.
  32734. * @param successCallback an optional success callback to be called after the optimization finished.
  32735. */
  32736. Mesh.prototype.optimizeIndices = function (successCallback) {
  32737. var _this = this;
  32738. var indices = this.getIndices();
  32739. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32740. if (!positions || !indices) {
  32741. return this;
  32742. }
  32743. var vectorPositions = new Array();
  32744. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32745. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32746. }
  32747. var dupes = new Array();
  32748. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32749. var realPos = vectorPositions.length - 1 - iteration;
  32750. var testedPosition = vectorPositions[realPos];
  32751. for (var j = 0; j < realPos; ++j) {
  32752. var againstPosition = vectorPositions[j];
  32753. if (testedPosition.equals(againstPosition)) {
  32754. dupes[realPos] = j;
  32755. break;
  32756. }
  32757. }
  32758. }, function () {
  32759. for (var i = 0; i < indices.length; ++i) {
  32760. indices[i] = dupes[indices[i]] || indices[i];
  32761. }
  32762. //indices are now reordered
  32763. var originalSubMeshes = _this.subMeshes.slice(0);
  32764. _this.setIndices(indices);
  32765. _this.subMeshes = originalSubMeshes;
  32766. if (successCallback) {
  32767. successCallback(_this);
  32768. }
  32769. });
  32770. return this;
  32771. };
  32772. Mesh.prototype.serialize = function (serializationObject) {
  32773. serializationObject.name = this.name;
  32774. serializationObject.id = this.id;
  32775. serializationObject.type = this.getClassName();
  32776. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32777. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32778. }
  32779. serializationObject.position = this.position.asArray();
  32780. if (this.rotationQuaternion) {
  32781. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32782. }
  32783. else if (this.rotation) {
  32784. serializationObject.rotation = this.rotation.asArray();
  32785. }
  32786. serializationObject.scaling = this.scaling.asArray();
  32787. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32788. serializationObject.isEnabled = this.isEnabled(false);
  32789. serializationObject.isVisible = this.isVisible;
  32790. serializationObject.infiniteDistance = this.infiniteDistance;
  32791. serializationObject.pickable = this.isPickable;
  32792. serializationObject.receiveShadows = this.receiveShadows;
  32793. serializationObject.billboardMode = this.billboardMode;
  32794. serializationObject.visibility = this.visibility;
  32795. serializationObject.checkCollisions = this.checkCollisions;
  32796. serializationObject.isBlocker = this.isBlocker;
  32797. // Parent
  32798. if (this.parent) {
  32799. serializationObject.parentId = this.parent.id;
  32800. }
  32801. // Geometry
  32802. serializationObject.isUnIndexed = this.isUnIndexed;
  32803. var geometry = this._geometry;
  32804. if (geometry) {
  32805. var geometryId = geometry.id;
  32806. serializationObject.geometryId = geometryId;
  32807. // SubMeshes
  32808. serializationObject.subMeshes = [];
  32809. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32810. var subMesh = this.subMeshes[subIndex];
  32811. serializationObject.subMeshes.push({
  32812. materialIndex: subMesh.materialIndex,
  32813. verticesStart: subMesh.verticesStart,
  32814. verticesCount: subMesh.verticesCount,
  32815. indexStart: subMesh.indexStart,
  32816. indexCount: subMesh.indexCount
  32817. });
  32818. }
  32819. }
  32820. // Material
  32821. if (this.material) {
  32822. serializationObject.materialId = this.material.id;
  32823. }
  32824. else {
  32825. this.material = null;
  32826. }
  32827. // Morph targets
  32828. if (this.morphTargetManager) {
  32829. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32830. }
  32831. // Skeleton
  32832. if (this.skeleton) {
  32833. serializationObject.skeletonId = this.skeleton.id;
  32834. }
  32835. // Physics
  32836. //TODO implement correct serialization for physics impostors.
  32837. var impostor = this.getPhysicsImpostor();
  32838. if (impostor) {
  32839. serializationObject.physicsMass = impostor.getParam("mass");
  32840. serializationObject.physicsFriction = impostor.getParam("friction");
  32841. serializationObject.physicsRestitution = impostor.getParam("mass");
  32842. serializationObject.physicsImpostor = impostor.type;
  32843. }
  32844. // Metadata
  32845. if (this.metadata) {
  32846. serializationObject.metadata = this.metadata;
  32847. }
  32848. // Instances
  32849. serializationObject.instances = [];
  32850. for (var index = 0; index < this.instances.length; index++) {
  32851. var instance = this.instances[index];
  32852. var serializationInstance = {
  32853. name: instance.name,
  32854. id: instance.id,
  32855. position: instance.position.asArray(),
  32856. scaling: instance.scaling.asArray()
  32857. };
  32858. if (instance.rotationQuaternion) {
  32859. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32860. }
  32861. else if (instance.rotation) {
  32862. serializationInstance.rotation = instance.rotation.asArray();
  32863. }
  32864. serializationObject.instances.push(serializationInstance);
  32865. // Animations
  32866. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32867. serializationInstance.ranges = instance.serializeAnimationRanges();
  32868. }
  32869. //
  32870. // Animations
  32871. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32872. serializationObject.ranges = this.serializeAnimationRanges();
  32873. // Layer mask
  32874. serializationObject.layerMask = this.layerMask;
  32875. // Alpha
  32876. serializationObject.alphaIndex = this.alphaIndex;
  32877. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32878. // Overlay
  32879. serializationObject.overlayAlpha = this.overlayAlpha;
  32880. serializationObject.overlayColor = this.overlayColor.asArray();
  32881. serializationObject.renderOverlay = this.renderOverlay;
  32882. // Fog
  32883. serializationObject.applyFog = this.applyFog;
  32884. // Action Manager
  32885. if (this.actionManager) {
  32886. serializationObject.actions = this.actionManager.serialize(this.name);
  32887. }
  32888. };
  32889. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32890. if (!this.geometry) {
  32891. return;
  32892. }
  32893. this._markSubMeshesAsAttributesDirty();
  32894. var morphTargetManager = this._morphTargetManager;
  32895. if (morphTargetManager && morphTargetManager.vertexCount) {
  32896. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32897. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32898. this.morphTargetManager = null;
  32899. return;
  32900. }
  32901. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32902. var morphTarget = morphTargetManager.getActiveTarget(index);
  32903. var positions = morphTarget.getPositions();
  32904. if (!positions) {
  32905. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32906. return;
  32907. }
  32908. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32909. var normals = morphTarget.getNormals();
  32910. if (normals) {
  32911. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32912. }
  32913. var tangents = morphTarget.getTangents();
  32914. if (tangents) {
  32915. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32916. }
  32917. }
  32918. }
  32919. else {
  32920. var index = 0;
  32921. // Positions
  32922. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32923. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32924. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32925. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32926. }
  32927. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32928. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32929. }
  32930. index++;
  32931. }
  32932. }
  32933. };
  32934. // Statics
  32935. /**
  32936. * Returns a new Mesh object parsed from the source provided.
  32937. * The parameter `parsedMesh` is the source.
  32938. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32939. */
  32940. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32941. var mesh;
  32942. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32943. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32944. }
  32945. else {
  32946. mesh = new Mesh(parsedMesh.name, scene);
  32947. }
  32948. mesh.id = parsedMesh.id;
  32949. if (BABYLON.Tags) {
  32950. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32951. }
  32952. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32953. if (parsedMesh.metadata !== undefined) {
  32954. mesh.metadata = parsedMesh.metadata;
  32955. }
  32956. if (parsedMesh.rotationQuaternion) {
  32957. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32958. }
  32959. else if (parsedMesh.rotation) {
  32960. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32961. }
  32962. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32963. if (parsedMesh.localMatrix) {
  32964. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32965. }
  32966. else if (parsedMesh.pivotMatrix) {
  32967. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32968. }
  32969. mesh.setEnabled(parsedMesh.isEnabled);
  32970. mesh.isVisible = parsedMesh.isVisible;
  32971. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32972. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32973. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32974. if (parsedMesh.applyFog !== undefined) {
  32975. mesh.applyFog = parsedMesh.applyFog;
  32976. }
  32977. if (parsedMesh.pickable !== undefined) {
  32978. mesh.isPickable = parsedMesh.pickable;
  32979. }
  32980. if (parsedMesh.alphaIndex !== undefined) {
  32981. mesh.alphaIndex = parsedMesh.alphaIndex;
  32982. }
  32983. mesh.receiveShadows = parsedMesh.receiveShadows;
  32984. mesh.billboardMode = parsedMesh.billboardMode;
  32985. if (parsedMesh.visibility !== undefined) {
  32986. mesh.visibility = parsedMesh.visibility;
  32987. }
  32988. mesh.checkCollisions = parsedMesh.checkCollisions;
  32989. if (parsedMesh.isBlocker !== undefined) {
  32990. mesh.isBlocker = parsedMesh.isBlocker;
  32991. }
  32992. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32993. // freezeWorldMatrix
  32994. if (parsedMesh.freezeWorldMatrix) {
  32995. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32996. }
  32997. // Parent
  32998. if (parsedMesh.parentId) {
  32999. mesh._waitingParentId = parsedMesh.parentId;
  33000. }
  33001. // Actions
  33002. if (parsedMesh.actions !== undefined) {
  33003. mesh._waitingActions = parsedMesh.actions;
  33004. }
  33005. // Overlay
  33006. if (parsedMesh.overlayAlpha !== undefined) {
  33007. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33008. }
  33009. if (parsedMesh.overlayColor !== undefined) {
  33010. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33011. }
  33012. if (parsedMesh.renderOverlay !== undefined) {
  33013. mesh.renderOverlay = parsedMesh.renderOverlay;
  33014. }
  33015. // Geometry
  33016. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33017. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33018. if (parsedMesh.delayLoadingFile) {
  33019. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33020. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33021. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33022. if (parsedMesh._binaryInfo) {
  33023. mesh._binaryInfo = parsedMesh._binaryInfo;
  33024. }
  33025. mesh._delayInfo = [];
  33026. if (parsedMesh.hasUVs) {
  33027. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33028. }
  33029. if (parsedMesh.hasUVs2) {
  33030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33031. }
  33032. if (parsedMesh.hasUVs3) {
  33033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33034. }
  33035. if (parsedMesh.hasUVs4) {
  33036. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33037. }
  33038. if (parsedMesh.hasUVs5) {
  33039. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33040. }
  33041. if (parsedMesh.hasUVs6) {
  33042. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33043. }
  33044. if (parsedMesh.hasColors) {
  33045. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33046. }
  33047. if (parsedMesh.hasMatricesIndices) {
  33048. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33049. }
  33050. if (parsedMesh.hasMatricesWeights) {
  33051. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33052. }
  33053. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33054. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33055. mesh._checkDelayState();
  33056. }
  33057. }
  33058. else {
  33059. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33060. }
  33061. // Material
  33062. if (parsedMesh.materialId) {
  33063. mesh.setMaterialByID(parsedMesh.materialId);
  33064. }
  33065. else {
  33066. mesh.material = null;
  33067. }
  33068. // Morph targets
  33069. if (parsedMesh.morphTargetManagerId > -1) {
  33070. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33071. }
  33072. // Skeleton
  33073. if (parsedMesh.skeletonId > -1) {
  33074. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33075. if (parsedMesh.numBoneInfluencers) {
  33076. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33077. }
  33078. }
  33079. // Animations
  33080. if (parsedMesh.animations) {
  33081. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33082. var parsedAnimation = parsedMesh.animations[animationIndex];
  33083. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33084. }
  33085. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33086. }
  33087. if (parsedMesh.autoAnimate) {
  33088. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33089. }
  33090. // Layer Mask
  33091. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33092. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33093. }
  33094. else {
  33095. mesh.layerMask = 0x0FFFFFFF;
  33096. }
  33097. // Physics
  33098. if (parsedMesh.physicsImpostor) {
  33099. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33100. mass: parsedMesh.physicsMass,
  33101. friction: parsedMesh.physicsFriction,
  33102. restitution: parsedMesh.physicsRestitution
  33103. }, scene);
  33104. }
  33105. // Instances
  33106. if (parsedMesh.instances) {
  33107. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33108. var parsedInstance = parsedMesh.instances[index];
  33109. var instance = mesh.createInstance(parsedInstance.name);
  33110. if (parsedInstance.id) {
  33111. instance.id = parsedInstance.id;
  33112. }
  33113. if (BABYLON.Tags) {
  33114. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33115. }
  33116. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33117. if (parsedInstance.parentId) {
  33118. instance._waitingParentId = parsedInstance.parentId;
  33119. }
  33120. if (parsedInstance.rotationQuaternion) {
  33121. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33122. }
  33123. else if (parsedInstance.rotation) {
  33124. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33125. }
  33126. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33127. instance.checkCollisions = mesh.checkCollisions;
  33128. if (parsedMesh.animations) {
  33129. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33130. parsedAnimation = parsedMesh.animations[animationIndex];
  33131. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33132. }
  33133. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33134. }
  33135. }
  33136. }
  33137. return mesh;
  33138. };
  33139. /**
  33140. * Creates a ribbon mesh.
  33141. * Please consider using the same method from the MeshBuilder class instead.
  33142. * 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.
  33143. *
  33144. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33145. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33146. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33147. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33148. * 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.
  33149. * 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.
  33150. * 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
  33151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33152. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33154. */
  33155. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33156. if (closeArray === void 0) { closeArray = false; }
  33157. if (updatable === void 0) { updatable = false; }
  33158. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33159. pathArray: pathArray,
  33160. closeArray: closeArray,
  33161. closePath: closePath,
  33162. offset: offset,
  33163. updatable: updatable,
  33164. sideOrientation: sideOrientation,
  33165. instance: instance
  33166. }, scene);
  33167. };
  33168. /**
  33169. * Creates a plane polygonal mesh. By default, this is a disc.
  33170. * Please consider using the same method from the MeshBuilder class instead.
  33171. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33172. * 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.
  33173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33174. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33176. */
  33177. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33178. if (scene === void 0) { scene = null; }
  33179. var options = {
  33180. radius: radius,
  33181. tessellation: tessellation,
  33182. sideOrientation: sideOrientation,
  33183. updatable: updatable
  33184. };
  33185. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33186. };
  33187. /**
  33188. * Creates a box mesh.
  33189. * Please consider using the same method from the MeshBuilder class instead.
  33190. * The parameter `size` sets the size (float) of each box side (default 1).
  33191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33192. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33194. */
  33195. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33196. if (scene === void 0) { scene = null; }
  33197. var options = {
  33198. size: size,
  33199. sideOrientation: sideOrientation,
  33200. updatable: updatable
  33201. };
  33202. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33203. };
  33204. /**
  33205. * Creates a sphere mesh.
  33206. * Please consider using the same method from the MeshBuilder class instead.
  33207. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33208. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33209. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33210. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33212. */
  33213. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33214. var options = {
  33215. segments: segments,
  33216. diameterX: diameter,
  33217. diameterY: diameter,
  33218. diameterZ: diameter,
  33219. sideOrientation: sideOrientation,
  33220. updatable: updatable
  33221. };
  33222. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33223. };
  33224. /**
  33225. * Creates a cylinder or a cone mesh.
  33226. * Please consider using the same method from the MeshBuilder class instead.
  33227. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33228. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33229. * 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.
  33230. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33231. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33232. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33233. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33235. */
  33236. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33237. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33238. if (scene !== undefined) {
  33239. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33240. updatable = scene;
  33241. }
  33242. scene = subdivisions;
  33243. subdivisions = 1;
  33244. }
  33245. var options = {
  33246. height: height,
  33247. diameterTop: diameterTop,
  33248. diameterBottom: diameterBottom,
  33249. tessellation: tessellation,
  33250. subdivisions: subdivisions,
  33251. sideOrientation: sideOrientation,
  33252. updatable: updatable
  33253. };
  33254. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33255. };
  33256. // Torus (Code from SharpDX.org)
  33257. /**
  33258. * Creates a torus mesh.
  33259. * Please consider using the same method from the MeshBuilder class instead.
  33260. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33261. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33262. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33264. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33266. */
  33267. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33268. var options = {
  33269. diameter: diameter,
  33270. thickness: thickness,
  33271. tessellation: tessellation,
  33272. sideOrientation: sideOrientation,
  33273. updatable: updatable
  33274. };
  33275. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33276. };
  33277. /**
  33278. * Creates a torus knot mesh.
  33279. * Please consider using the same method from the MeshBuilder class instead.
  33280. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33281. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33282. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33283. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33285. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33287. */
  33288. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33289. var options = {
  33290. radius: radius,
  33291. tube: tube,
  33292. radialSegments: radialSegments,
  33293. tubularSegments: tubularSegments,
  33294. p: p,
  33295. q: q,
  33296. sideOrientation: sideOrientation,
  33297. updatable: updatable
  33298. };
  33299. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33300. };
  33301. /**
  33302. * Creates a line mesh.
  33303. * Please consider using the same method from the MeshBuilder class instead.
  33304. * 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.
  33305. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33306. * The parameter `points` is an array successive Vector3.
  33307. * 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
  33308. * When updating an instance, remember that only point positions can change, not the number of points.
  33309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33310. */
  33311. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33312. if (scene === void 0) { scene = null; }
  33313. if (updatable === void 0) { updatable = false; }
  33314. if (instance === void 0) { instance = null; }
  33315. var options = {
  33316. points: points,
  33317. updatable: updatable,
  33318. instance: instance
  33319. };
  33320. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33321. };
  33322. /**
  33323. * Creates a dashed line mesh.
  33324. * Please consider using the same method from the MeshBuilder class instead.
  33325. * 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.
  33326. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33327. * The parameter `points` is an array successive Vector3.
  33328. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33329. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33330. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33331. * 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
  33332. * When updating an instance, remember that only point positions can change, not the number of points.
  33333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33334. */
  33335. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33336. if (scene === void 0) { scene = null; }
  33337. var options = {
  33338. points: points,
  33339. dashSize: dashSize,
  33340. gapSize: gapSize,
  33341. dashNb: dashNb,
  33342. updatable: updatable,
  33343. instance: instance
  33344. };
  33345. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33346. };
  33347. /**
  33348. * Creates a polygon mesh.
  33349. * Please consider using the same method from the MeshBuilder class instead.
  33350. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33351. * 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.
  33352. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33354. * Remember you can only change the shape positions, not their number when updating a polygon.
  33355. */
  33356. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33357. var options = {
  33358. shape: shape,
  33359. holes: holes,
  33360. updatable: updatable,
  33361. sideOrientation: sideOrientation
  33362. };
  33363. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33364. };
  33365. /**
  33366. * Creates an extruded polygon mesh, with depth in the Y direction.
  33367. * Please consider using the same method from the MeshBuilder class instead.
  33368. */
  33369. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33370. var options = {
  33371. shape: shape,
  33372. holes: holes,
  33373. depth: depth,
  33374. updatable: updatable,
  33375. sideOrientation: sideOrientation
  33376. };
  33377. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33378. };
  33379. /**
  33380. * Creates an extruded shape mesh.
  33381. * 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.
  33382. * Please consider using the same method from the MeshBuilder class instead.
  33383. *
  33384. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33385. * 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
  33386. * extruded along the Z axis.
  33387. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33388. * 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.
  33389. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33390. * 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
  33391. * 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
  33392. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33394. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33396. */
  33397. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33398. if (scene === void 0) { scene = null; }
  33399. var options = {
  33400. shape: shape,
  33401. path: path,
  33402. scale: scale,
  33403. rotation: rotation,
  33404. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33405. sideOrientation: sideOrientation,
  33406. instance: instance,
  33407. updatable: updatable
  33408. };
  33409. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33410. };
  33411. /**
  33412. * Creates an custom extruded shape mesh.
  33413. * 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.
  33414. * Please consider using the same method from the MeshBuilder class instead.
  33415. *
  33416. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33417. * 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
  33418. * extruded along the Z axis.
  33419. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33420. * 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
  33421. * and the distance of this point from the begining of the path :
  33422. * ```javascript
  33423. * var rotationFunction = function(i, distance) {
  33424. * // do things
  33425. * return rotationValue; }
  33426. * ```
  33427. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33428. * 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
  33429. * and the distance of this point from the begining of the path :
  33430. * ```javascript
  33431. * var scaleFunction = function(i, distance) {
  33432. * // do things
  33433. * return scaleValue;}
  33434. * ```
  33435. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33436. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33437. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33438. * 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
  33439. * 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
  33440. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33441. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33442. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33444. */
  33445. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33446. var options = {
  33447. shape: shape,
  33448. path: path,
  33449. scaleFunction: scaleFunction,
  33450. rotationFunction: rotationFunction,
  33451. ribbonCloseArray: ribbonCloseArray,
  33452. ribbonClosePath: ribbonClosePath,
  33453. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33454. sideOrientation: sideOrientation,
  33455. instance: instance,
  33456. updatable: updatable
  33457. };
  33458. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33459. };
  33460. /**
  33461. * Creates lathe mesh.
  33462. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33463. * Please consider using the same method from the MeshBuilder class instead.
  33464. * 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
  33465. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33466. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33467. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33468. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33469. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33471. */
  33472. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33473. var options = {
  33474. shape: shape,
  33475. radius: radius,
  33476. tessellation: tessellation,
  33477. sideOrientation: sideOrientation,
  33478. updatable: updatable
  33479. };
  33480. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33481. };
  33482. /**
  33483. * Creates a plane mesh.
  33484. * Please consider using the same method from the MeshBuilder class instead.
  33485. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33487. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33489. */
  33490. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33491. var options = {
  33492. size: size,
  33493. width: size,
  33494. height: size,
  33495. sideOrientation: sideOrientation,
  33496. updatable: updatable
  33497. };
  33498. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33499. };
  33500. /**
  33501. * Creates a ground mesh.
  33502. * Please consider using the same method from the MeshBuilder class instead.
  33503. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33504. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33506. */
  33507. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33508. var options = {
  33509. width: width,
  33510. height: height,
  33511. subdivisions: subdivisions,
  33512. updatable: updatable
  33513. };
  33514. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33515. };
  33516. /**
  33517. * Creates a tiled ground mesh.
  33518. * Please consider using the same method from the MeshBuilder class instead.
  33519. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33520. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33521. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33522. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33523. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33524. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33528. var options = {
  33529. xmin: xmin,
  33530. zmin: zmin,
  33531. xmax: xmax,
  33532. zmax: zmax,
  33533. subdivisions: subdivisions,
  33534. precision: precision,
  33535. updatable: updatable
  33536. };
  33537. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33538. };
  33539. /**
  33540. * Creates a ground mesh from a height map.
  33541. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33542. * Please consider using the same method from the MeshBuilder class instead.
  33543. * The parameter `url` sets the URL of the height map image resource.
  33544. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33545. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33546. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33547. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33548. * 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).
  33549. * This function is passed the newly built mesh :
  33550. * ```javascript
  33551. * function(mesh) { // do things
  33552. * return; }
  33553. * ```
  33554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33555. */
  33556. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33557. var options = {
  33558. width: width,
  33559. height: height,
  33560. subdivisions: subdivisions,
  33561. minHeight: minHeight,
  33562. maxHeight: maxHeight,
  33563. updatable: updatable,
  33564. onReady: onReady
  33565. };
  33566. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33567. };
  33568. /**
  33569. * Creates a tube mesh.
  33570. * 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.
  33571. * Please consider using the same method from the MeshBuilder class instead.
  33572. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33573. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33574. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33575. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33576. * 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.
  33577. * It must return a radius value (positive float) :
  33578. * ```javascript
  33579. * var radiusFunction = function(i, distance) {
  33580. * // do things
  33581. * return radius; }
  33582. * ```
  33583. * 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
  33584. * 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
  33585. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33586. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33588. */
  33589. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33590. var options = {
  33591. path: path,
  33592. radius: radius,
  33593. tessellation: tessellation,
  33594. radiusFunction: radiusFunction,
  33595. arc: 1,
  33596. cap: cap,
  33597. updatable: updatable,
  33598. sideOrientation: sideOrientation,
  33599. instance: instance
  33600. };
  33601. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33602. };
  33603. /**
  33604. * Creates a polyhedron mesh.
  33605. * Please consider using the same method from the MeshBuilder class instead.
  33606. * 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
  33607. * to choose the wanted type.
  33608. * The parameter `size` (positive float, default 1) sets the polygon size.
  33609. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33610. * 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`.
  33611. * 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
  33612. * 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)`).
  33613. * 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
  33614. * 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.
  33615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33616. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33618. */
  33619. Mesh.CreatePolyhedron = function (name, options, scene) {
  33620. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33621. };
  33622. /**
  33623. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33624. * Please consider using the same method from the MeshBuilder class instead.
  33625. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33626. * 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`).
  33627. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33628. * 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.
  33629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33630. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33632. */
  33633. Mesh.CreateIcoSphere = function (name, options, scene) {
  33634. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33635. };
  33636. /**
  33637. * Creates a decal mesh.
  33638. * Please consider using the same method from the MeshBuilder class instead.
  33639. * 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.
  33640. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33641. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33642. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33643. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33644. */
  33645. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33646. var options = {
  33647. position: position,
  33648. normal: normal,
  33649. size: size,
  33650. angle: angle
  33651. };
  33652. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33653. };
  33654. // Skeletons
  33655. /**
  33656. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33657. */
  33658. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33659. if (!this._sourcePositions) {
  33660. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33661. if (!source) {
  33662. return this._sourcePositions;
  33663. }
  33664. this._sourcePositions = new Float32Array(source);
  33665. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33666. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33667. }
  33668. }
  33669. return this._sourcePositions;
  33670. };
  33671. /**
  33672. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33673. */
  33674. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33675. if (!this._sourceNormals) {
  33676. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33677. if (!source) {
  33678. return this._sourceNormals;
  33679. }
  33680. this._sourceNormals = new Float32Array(source);
  33681. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33682. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33683. }
  33684. }
  33685. return this._sourceNormals;
  33686. };
  33687. /**
  33688. * Updates the vertex buffer by applying transformation from the bones.
  33689. * Returns the Mesh.
  33690. *
  33691. * @param {skeleton} skeleton to apply
  33692. */
  33693. Mesh.prototype.applySkeleton = function (skeleton) {
  33694. if (!this.geometry) {
  33695. return this;
  33696. }
  33697. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33698. return this;
  33699. }
  33700. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33701. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33702. return this;
  33703. }
  33704. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33705. return this;
  33706. }
  33707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33708. return this;
  33709. }
  33710. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33711. return this;
  33712. }
  33713. if (!this._sourcePositions) {
  33714. var submeshes = this.subMeshes.slice();
  33715. this.setPositionsForCPUSkinning();
  33716. this.subMeshes = submeshes;
  33717. }
  33718. if (!this._sourceNormals) {
  33719. this.setNormalsForCPUSkinning();
  33720. }
  33721. // positionsData checks for not being Float32Array will only pass at most once
  33722. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33723. if (!positionsData) {
  33724. return this;
  33725. }
  33726. if (!(positionsData instanceof Float32Array)) {
  33727. positionsData = new Float32Array(positionsData);
  33728. }
  33729. // normalsData checks for not being Float32Array will only pass at most once
  33730. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33731. if (!normalsData) {
  33732. return this;
  33733. }
  33734. if (!(normalsData instanceof Float32Array)) {
  33735. normalsData = new Float32Array(normalsData);
  33736. }
  33737. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33738. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33739. if (!matricesWeightsData || !matricesIndicesData) {
  33740. return this;
  33741. }
  33742. var needExtras = this.numBoneInfluencers > 4;
  33743. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33744. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33745. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33746. var tempVector3 = BABYLON.Vector3.Zero();
  33747. var finalMatrix = new BABYLON.Matrix();
  33748. var tempMatrix = new BABYLON.Matrix();
  33749. var matWeightIdx = 0;
  33750. var inf;
  33751. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33752. var weight;
  33753. for (inf = 0; inf < 4; inf++) {
  33754. weight = matricesWeightsData[matWeightIdx + inf];
  33755. if (weight > 0) {
  33756. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33757. finalMatrix.addToSelf(tempMatrix);
  33758. }
  33759. else
  33760. break;
  33761. }
  33762. if (needExtras) {
  33763. for (inf = 0; inf < 4; inf++) {
  33764. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33765. if (weight > 0) {
  33766. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33767. finalMatrix.addToSelf(tempMatrix);
  33768. }
  33769. else
  33770. break;
  33771. }
  33772. }
  33773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33774. tempVector3.toArray(positionsData, index);
  33775. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33776. tempVector3.toArray(normalsData, index);
  33777. finalMatrix.reset();
  33778. }
  33779. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33780. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33781. return this;
  33782. };
  33783. // Tools
  33784. /**
  33785. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33786. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33787. */
  33788. Mesh.MinMax = function (meshes) {
  33789. var minVector = null;
  33790. var maxVector = null;
  33791. meshes.forEach(function (mesh, index, array) {
  33792. var boundingInfo = mesh.getBoundingInfo();
  33793. var boundingBox = boundingInfo.boundingBox;
  33794. if (!minVector || !maxVector) {
  33795. minVector = boundingBox.minimumWorld;
  33796. maxVector = boundingBox.maximumWorld;
  33797. }
  33798. else {
  33799. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33800. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33801. }
  33802. });
  33803. if (!minVector || !maxVector) {
  33804. return {
  33805. min: BABYLON.Vector3.Zero(),
  33806. max: BABYLON.Vector3.Zero()
  33807. };
  33808. }
  33809. return {
  33810. min: minVector,
  33811. max: maxVector
  33812. };
  33813. };
  33814. /**
  33815. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33816. */
  33817. Mesh.Center = function (meshesOrMinMaxVector) {
  33818. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33819. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33820. };
  33821. /**
  33822. * Merge the array of meshes into a single mesh for performance reasons.
  33823. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33824. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33825. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33826. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33827. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33828. */
  33829. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33830. if (disposeSource === void 0) { disposeSource = true; }
  33831. var index;
  33832. if (!allow32BitsIndices) {
  33833. var totalVertices = 0;
  33834. // Counting vertices
  33835. for (index = 0; index < meshes.length; index++) {
  33836. if (meshes[index]) {
  33837. totalVertices += meshes[index].getTotalVertices();
  33838. if (totalVertices > 65536) {
  33839. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33840. return null;
  33841. }
  33842. }
  33843. }
  33844. }
  33845. // Merge
  33846. var vertexData = null;
  33847. var otherVertexData;
  33848. var indiceArray = new Array();
  33849. var source = null;
  33850. for (index = 0; index < meshes.length; index++) {
  33851. if (meshes[index]) {
  33852. meshes[index].computeWorldMatrix(true);
  33853. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33854. otherVertexData.transform(meshes[index].getWorldMatrix());
  33855. if (vertexData) {
  33856. vertexData.merge(otherVertexData);
  33857. }
  33858. else {
  33859. vertexData = otherVertexData;
  33860. source = meshes[index];
  33861. }
  33862. if (subdivideWithSubMeshes) {
  33863. indiceArray.push(meshes[index].getTotalIndices());
  33864. }
  33865. }
  33866. }
  33867. source = source;
  33868. if (!meshSubclass) {
  33869. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33870. }
  33871. vertexData.applyToMesh(meshSubclass);
  33872. // Setting properties
  33873. meshSubclass.material = source.material;
  33874. meshSubclass.checkCollisions = source.checkCollisions;
  33875. // Cleaning
  33876. if (disposeSource) {
  33877. for (index = 0; index < meshes.length; index++) {
  33878. if (meshes[index]) {
  33879. meshes[index].dispose();
  33880. }
  33881. }
  33882. }
  33883. // Subdivide
  33884. if (subdivideWithSubMeshes) {
  33885. //-- Suppresions du submesh global
  33886. meshSubclass.releaseSubMeshes();
  33887. index = 0;
  33888. var offset = 0;
  33889. //-- aplique la subdivision en fonction du tableau d'indices
  33890. while (index < indiceArray.length) {
  33891. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33892. offset += indiceArray[index];
  33893. index++;
  33894. }
  33895. }
  33896. return meshSubclass;
  33897. };
  33898. // Consts
  33899. Mesh._FRONTSIDE = 0;
  33900. Mesh._BACKSIDE = 1;
  33901. Mesh._DOUBLESIDE = 2;
  33902. Mesh._DEFAULTSIDE = 0;
  33903. Mesh._NO_CAP = 0;
  33904. Mesh._CAP_START = 1;
  33905. Mesh._CAP_END = 2;
  33906. Mesh._CAP_ALL = 3;
  33907. return Mesh;
  33908. }(BABYLON.AbstractMesh));
  33909. BABYLON.Mesh = Mesh;
  33910. })(BABYLON || (BABYLON = {}));
  33911. //# sourceMappingURL=babylon.mesh.js.map
  33912. var BABYLON;
  33913. (function (BABYLON) {
  33914. var BaseSubMesh = /** @class */ (function () {
  33915. function BaseSubMesh() {
  33916. }
  33917. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33918. get: function () {
  33919. return this._materialEffect;
  33920. },
  33921. enumerable: true,
  33922. configurable: true
  33923. });
  33924. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33925. if (defines === void 0) { defines = null; }
  33926. if (this._materialEffect === effect) {
  33927. if (!effect) {
  33928. this._materialDefines = null;
  33929. }
  33930. return;
  33931. }
  33932. this._materialDefines = defines;
  33933. this._materialEffect = effect;
  33934. };
  33935. return BaseSubMesh;
  33936. }());
  33937. BABYLON.BaseSubMesh = BaseSubMesh;
  33938. var SubMesh = /** @class */ (function (_super) {
  33939. __extends(SubMesh, _super);
  33940. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33941. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33942. var _this = _super.call(this) || this;
  33943. _this.materialIndex = materialIndex;
  33944. _this.verticesStart = verticesStart;
  33945. _this.verticesCount = verticesCount;
  33946. _this.indexStart = indexStart;
  33947. _this.indexCount = indexCount;
  33948. _this._renderId = 0;
  33949. _this._mesh = mesh;
  33950. _this._renderingMesh = renderingMesh || mesh;
  33951. mesh.subMeshes.push(_this);
  33952. _this._trianglePlanes = [];
  33953. _this._id = mesh.subMeshes.length - 1;
  33954. if (createBoundingBox) {
  33955. _this.refreshBoundingInfo();
  33956. mesh.computeWorldMatrix(true);
  33957. }
  33958. return _this;
  33959. }
  33960. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33961. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33962. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33963. };
  33964. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33965. get: function () {
  33966. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33967. },
  33968. enumerable: true,
  33969. configurable: true
  33970. });
  33971. /**
  33972. * Returns the submesh BoudingInfo object.
  33973. */
  33974. SubMesh.prototype.getBoundingInfo = function () {
  33975. if (this.IsGlobal) {
  33976. return this._mesh.getBoundingInfo();
  33977. }
  33978. return this._boundingInfo;
  33979. };
  33980. /**
  33981. * Sets the submesh BoundingInfo.
  33982. * Return the SubMesh.
  33983. */
  33984. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33985. this._boundingInfo = boundingInfo;
  33986. return this;
  33987. };
  33988. /**
  33989. * Returns the mesh of the current submesh.
  33990. */
  33991. SubMesh.prototype.getMesh = function () {
  33992. return this._mesh;
  33993. };
  33994. /**
  33995. * Returns the rendering mesh of the submesh.
  33996. */
  33997. SubMesh.prototype.getRenderingMesh = function () {
  33998. return this._renderingMesh;
  33999. };
  34000. /**
  34001. * Returns the submesh material.
  34002. */
  34003. SubMesh.prototype.getMaterial = function () {
  34004. var rootMaterial = this._renderingMesh.material;
  34005. if (rootMaterial === null || rootMaterial === undefined) {
  34006. return this._mesh.getScene().defaultMaterial;
  34007. }
  34008. else if (rootMaterial.getSubMaterial) {
  34009. var multiMaterial = rootMaterial;
  34010. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34011. if (this._currentMaterial !== effectiveMaterial) {
  34012. this._currentMaterial = effectiveMaterial;
  34013. this._materialDefines = null;
  34014. }
  34015. return effectiveMaterial;
  34016. }
  34017. return rootMaterial;
  34018. };
  34019. // Methods
  34020. /**
  34021. * Sets a new updated BoundingInfo object to the submesh.
  34022. * Returns the SubMesh.
  34023. */
  34024. SubMesh.prototype.refreshBoundingInfo = function () {
  34025. this._lastColliderWorldVertices = null;
  34026. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34027. return this;
  34028. }
  34029. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34030. if (!data) {
  34031. this._boundingInfo = this._mesh.getBoundingInfo();
  34032. return this;
  34033. }
  34034. var indices = this._renderingMesh.getIndices();
  34035. var extend;
  34036. //is this the only submesh?
  34037. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34038. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34039. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34040. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34041. }
  34042. else {
  34043. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34044. }
  34045. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34046. return this;
  34047. };
  34048. SubMesh.prototype._checkCollision = function (collider) {
  34049. var boundingInfo = this.getBoundingInfo();
  34050. return boundingInfo._checkCollision(collider);
  34051. };
  34052. /**
  34053. * Updates the submesh BoundingInfo.
  34054. * Returns the Submesh.
  34055. */
  34056. SubMesh.prototype.updateBoundingInfo = function (world) {
  34057. var boundingInfo = this.getBoundingInfo();
  34058. if (!boundingInfo) {
  34059. this.refreshBoundingInfo();
  34060. boundingInfo = this.getBoundingInfo();
  34061. }
  34062. boundingInfo.update(world);
  34063. return this;
  34064. };
  34065. /**
  34066. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34067. * Boolean returned.
  34068. */
  34069. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34070. var boundingInfo = this.getBoundingInfo();
  34071. if (!boundingInfo) {
  34072. return false;
  34073. }
  34074. return boundingInfo.isInFrustum(frustumPlanes);
  34075. };
  34076. /**
  34077. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34078. * Boolean returned.
  34079. */
  34080. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34081. var boundingInfo = this.getBoundingInfo();
  34082. if (!boundingInfo) {
  34083. return false;
  34084. }
  34085. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34086. };
  34087. /**
  34088. * Renders the submesh.
  34089. * Returns it.
  34090. */
  34091. SubMesh.prototype.render = function (enableAlphaMode) {
  34092. this._renderingMesh.render(this, enableAlphaMode);
  34093. return this;
  34094. };
  34095. /**
  34096. * Returns a new Index Buffer.
  34097. * Type returned : WebGLBuffer.
  34098. */
  34099. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34100. if (!this._linesIndexBuffer) {
  34101. var linesIndices = [];
  34102. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34103. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34104. }
  34105. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34106. this.linesIndexCount = linesIndices.length;
  34107. }
  34108. return this._linesIndexBuffer;
  34109. };
  34110. /**
  34111. * True is the passed Ray intersects the submesh bounding box.
  34112. * Boolean returned.
  34113. */
  34114. SubMesh.prototype.canIntersects = function (ray) {
  34115. var boundingInfo = this.getBoundingInfo();
  34116. if (!boundingInfo) {
  34117. return false;
  34118. }
  34119. return ray.intersectsBox(boundingInfo.boundingBox);
  34120. };
  34121. /**
  34122. * Returns an object IntersectionInfo.
  34123. */
  34124. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34125. var intersectInfo = null;
  34126. var material = this.getMaterial();
  34127. if (!material) {
  34128. return null;
  34129. }
  34130. switch (material.fillMode) {
  34131. case BABYLON.Material.PointListDrawMode:
  34132. case BABYLON.Material.LineListDrawMode:
  34133. case BABYLON.Material.LineLoopDrawMode:
  34134. case BABYLON.Material.LineStripDrawMode:
  34135. case BABYLON.Material.TriangleFanDrawMode:
  34136. case BABYLON.Material.TriangleStripDrawMode:
  34137. return null;
  34138. }
  34139. // LineMesh first as it's also a Mesh...
  34140. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34141. var lineMesh = this._mesh;
  34142. // Line test
  34143. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34144. var p0 = positions[indices[index]];
  34145. var p1 = positions[indices[index + 1]];
  34146. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34147. if (length < 0) {
  34148. continue;
  34149. }
  34150. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34151. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34152. if (fastCheck) {
  34153. break;
  34154. }
  34155. }
  34156. }
  34157. }
  34158. else {
  34159. // Triangles test
  34160. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34161. var p0 = positions[indices[index]];
  34162. var p1 = positions[indices[index + 1]];
  34163. var p2 = positions[indices[index + 2]];
  34164. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34165. if (currentIntersectInfo) {
  34166. if (currentIntersectInfo.distance < 0) {
  34167. continue;
  34168. }
  34169. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34170. intersectInfo = currentIntersectInfo;
  34171. intersectInfo.faceId = index / 3;
  34172. if (fastCheck) {
  34173. break;
  34174. }
  34175. }
  34176. }
  34177. }
  34178. }
  34179. return intersectInfo;
  34180. };
  34181. SubMesh.prototype._rebuild = function () {
  34182. if (this._linesIndexBuffer) {
  34183. this._linesIndexBuffer = null;
  34184. }
  34185. };
  34186. // Clone
  34187. /**
  34188. * Creates a new Submesh from the passed Mesh.
  34189. */
  34190. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34191. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34192. if (!this.IsGlobal) {
  34193. var boundingInfo = this.getBoundingInfo();
  34194. if (!boundingInfo) {
  34195. return result;
  34196. }
  34197. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34198. }
  34199. return result;
  34200. };
  34201. // Dispose
  34202. /**
  34203. * Disposes the Submesh.
  34204. * Returns nothing.
  34205. */
  34206. SubMesh.prototype.dispose = function () {
  34207. if (this._linesIndexBuffer) {
  34208. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34209. this._linesIndexBuffer = null;
  34210. }
  34211. // Remove from mesh
  34212. var index = this._mesh.subMeshes.indexOf(this);
  34213. this._mesh.subMeshes.splice(index, 1);
  34214. };
  34215. // Statics
  34216. /**
  34217. * Creates a new Submesh from the passed parameters :
  34218. * - materialIndex (integer) : the index of the main mesh material.
  34219. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34220. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34221. * - mesh (Mesh) : the main mesh to create the submesh from.
  34222. * - renderingMesh (optional Mesh) : rendering mesh.
  34223. */
  34224. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34225. var minVertexIndex = Number.MAX_VALUE;
  34226. var maxVertexIndex = -Number.MAX_VALUE;
  34227. renderingMesh = (renderingMesh || mesh);
  34228. var indices = renderingMesh.getIndices();
  34229. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34230. var vertexIndex = indices[index];
  34231. if (vertexIndex < minVertexIndex)
  34232. minVertexIndex = vertexIndex;
  34233. if (vertexIndex > maxVertexIndex)
  34234. maxVertexIndex = vertexIndex;
  34235. }
  34236. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34237. };
  34238. return SubMesh;
  34239. }(BaseSubMesh));
  34240. BABYLON.SubMesh = SubMesh;
  34241. })(BABYLON || (BABYLON = {}));
  34242. //# sourceMappingURL=babylon.subMesh.js.map
  34243. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34244. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34245. s = arguments[i];
  34246. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34247. t[p] = s[p];
  34248. }
  34249. return t;
  34250. };
  34251. var BABYLON;
  34252. (function (BABYLON) {
  34253. /**
  34254. * Manages the defines for the Material
  34255. */
  34256. var MaterialDefines = /** @class */ (function () {
  34257. function MaterialDefines() {
  34258. this._isDirty = true;
  34259. /** @hidden */
  34260. this._areLightsDirty = true;
  34261. /** @hidden */
  34262. this._areAttributesDirty = true;
  34263. /** @hidden */
  34264. this._areTexturesDirty = true;
  34265. /** @hidden */
  34266. this._areFresnelDirty = true;
  34267. /** @hidden */
  34268. this._areMiscDirty = true;
  34269. /** @hidden */
  34270. this._areImageProcessingDirty = true;
  34271. /** @hidden */
  34272. this._normals = false;
  34273. /** @hidden */
  34274. this._uvs = false;
  34275. /** @hidden */
  34276. this._needNormals = false;
  34277. /** @hidden */
  34278. this._needUVs = false;
  34279. }
  34280. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34281. /**
  34282. * Specifies if the material needs to be re-calculated
  34283. */
  34284. get: function () {
  34285. return this._isDirty;
  34286. },
  34287. enumerable: true,
  34288. configurable: true
  34289. });
  34290. /**
  34291. * Marks the material to indicate that it has been re-calculated
  34292. */
  34293. MaterialDefines.prototype.markAsProcessed = function () {
  34294. this._isDirty = false;
  34295. this._areAttributesDirty = false;
  34296. this._areTexturesDirty = false;
  34297. this._areFresnelDirty = false;
  34298. this._areLightsDirty = false;
  34299. this._areMiscDirty = false;
  34300. this._areImageProcessingDirty = false;
  34301. };
  34302. /**
  34303. * Marks the material to indicate that it needs to be re-calculated
  34304. */
  34305. MaterialDefines.prototype.markAsUnprocessed = function () {
  34306. this._isDirty = true;
  34307. };
  34308. /**
  34309. * Marks the material to indicate all of its defines need to be re-calculated
  34310. */
  34311. MaterialDefines.prototype.markAllAsDirty = function () {
  34312. this._areTexturesDirty = true;
  34313. this._areAttributesDirty = true;
  34314. this._areLightsDirty = true;
  34315. this._areFresnelDirty = true;
  34316. this._areMiscDirty = true;
  34317. this._areImageProcessingDirty = true;
  34318. this._isDirty = true;
  34319. };
  34320. /**
  34321. * Marks the material to indicate that image processing needs to be re-calculated
  34322. */
  34323. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34324. this._areImageProcessingDirty = true;
  34325. this._isDirty = true;
  34326. };
  34327. /**
  34328. * Marks the material to indicate the lights need to be re-calculated
  34329. */
  34330. MaterialDefines.prototype.markAsLightDirty = function () {
  34331. this._areLightsDirty = true;
  34332. this._isDirty = true;
  34333. };
  34334. /**
  34335. * Marks the attribute state as changed
  34336. */
  34337. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34338. this._areAttributesDirty = true;
  34339. this._isDirty = true;
  34340. };
  34341. /**
  34342. * Marks the texture state as changed
  34343. */
  34344. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34345. this._areTexturesDirty = true;
  34346. this._isDirty = true;
  34347. };
  34348. /**
  34349. * Marks the fresnel state as changed
  34350. */
  34351. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34352. this._areFresnelDirty = true;
  34353. this._isDirty = true;
  34354. };
  34355. /**
  34356. * Marks the misc state as changed
  34357. */
  34358. MaterialDefines.prototype.markAsMiscDirty = function () {
  34359. this._areMiscDirty = true;
  34360. this._isDirty = true;
  34361. };
  34362. /**
  34363. * Rebuilds the material defines
  34364. */
  34365. MaterialDefines.prototype.rebuild = function () {
  34366. if (this._keys) {
  34367. delete this._keys;
  34368. }
  34369. this._keys = [];
  34370. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34371. var key = _a[_i];
  34372. if (key[0] === "_") {
  34373. continue;
  34374. }
  34375. this._keys.push(key);
  34376. }
  34377. };
  34378. /**
  34379. * Specifies if two material defines are equal
  34380. * @param other - A material define instance to compare to
  34381. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34382. */
  34383. MaterialDefines.prototype.isEqual = function (other) {
  34384. if (this._keys.length !== other._keys.length) {
  34385. return false;
  34386. }
  34387. for (var index = 0; index < this._keys.length; index++) {
  34388. var prop = this._keys[index];
  34389. if (this[prop] !== other[prop]) {
  34390. return false;
  34391. }
  34392. }
  34393. return true;
  34394. };
  34395. /**
  34396. * Clones this instance's defines to another instance
  34397. * @param other - material defines to clone values to
  34398. */
  34399. MaterialDefines.prototype.cloneTo = function (other) {
  34400. if (this._keys.length !== other._keys.length) {
  34401. other._keys = this._keys.slice(0);
  34402. }
  34403. for (var index = 0; index < this._keys.length; index++) {
  34404. var prop = this._keys[index];
  34405. other[prop] = this[prop];
  34406. }
  34407. };
  34408. /**
  34409. * Resets the material define values
  34410. */
  34411. MaterialDefines.prototype.reset = function () {
  34412. for (var index = 0; index < this._keys.length; index++) {
  34413. var prop = this._keys[index];
  34414. var type = typeof this[prop];
  34415. switch (type) {
  34416. case "number":
  34417. this[prop] = 0;
  34418. break;
  34419. case "string":
  34420. this[prop] = "";
  34421. break;
  34422. default:
  34423. this[prop] = false;
  34424. break;
  34425. }
  34426. }
  34427. };
  34428. /**
  34429. * Converts the material define values to a string
  34430. * @returns - String of material define information
  34431. */
  34432. MaterialDefines.prototype.toString = function () {
  34433. var result = "";
  34434. for (var index = 0; index < this._keys.length; index++) {
  34435. var prop = this._keys[index];
  34436. var value = this[prop];
  34437. var type = typeof value;
  34438. switch (type) {
  34439. case "number":
  34440. case "string":
  34441. result += "#define " + prop + " " + value + "\n";
  34442. break;
  34443. default:
  34444. if (value) {
  34445. result += "#define " + prop + "\n";
  34446. }
  34447. break;
  34448. }
  34449. }
  34450. return result;
  34451. };
  34452. return MaterialDefines;
  34453. }());
  34454. BABYLON.MaterialDefines = MaterialDefines;
  34455. /**
  34456. * Base class for the main features of a material in Babylon.js
  34457. */
  34458. var Material = /** @class */ (function () {
  34459. /**
  34460. * Creates a material instance
  34461. * @param name defines the name of the material
  34462. * @param scene defines the scene to reference
  34463. * @param doNotAdd specifies if the material should be added to the scene
  34464. */
  34465. function Material(name, scene, doNotAdd) {
  34466. /**
  34467. * Specifies if the ready state should be checked on each call
  34468. */
  34469. this.checkReadyOnEveryCall = false;
  34470. /**
  34471. * Specifies if the ready state should be checked once
  34472. */
  34473. this.checkReadyOnlyOnce = false;
  34474. /**
  34475. * The state of the material
  34476. */
  34477. this.state = "";
  34478. /**
  34479. * The alpha value of the material
  34480. */
  34481. this._alpha = 1.0;
  34482. /**
  34483. * Specifies if back face culling is enabled
  34484. */
  34485. this._backFaceCulling = true;
  34486. /**
  34487. * Specifies if the material should be serialized
  34488. */
  34489. this.doNotSerialize = false;
  34490. /**
  34491. * Specifies if the effect should be stored on sub meshes
  34492. */
  34493. this.storeEffectOnSubMeshes = false;
  34494. /**
  34495. * An event triggered when the material is disposed
  34496. */
  34497. this.onDisposeObservable = new BABYLON.Observable();
  34498. /**
  34499. * An event triggered when the material is bound
  34500. */
  34501. this.onBindObservable = new BABYLON.Observable();
  34502. /**
  34503. * An event triggered when the material is unbound
  34504. */
  34505. this.onUnBindObservable = new BABYLON.Observable();
  34506. /**
  34507. * Stores the value of the alpha mode
  34508. */
  34509. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34510. /**
  34511. * Stores the state of the need depth pre-pass value
  34512. */
  34513. this._needDepthPrePass = false;
  34514. /**
  34515. * Specifies if depth writing should be disabled
  34516. */
  34517. this.disableDepthWrite = false;
  34518. /**
  34519. * Specifies if depth writing should be forced
  34520. */
  34521. this.forceDepthWrite = false;
  34522. /**
  34523. * Specifies if there should be a separate pass for culling
  34524. */
  34525. this.separateCullingPass = false;
  34526. /**
  34527. * Stores the state specifing if fog should be enabled
  34528. */
  34529. this._fogEnabled = true;
  34530. /**
  34531. * Stores the size of points
  34532. */
  34533. this.pointSize = 1.0;
  34534. /**
  34535. * Stores the z offset value
  34536. */
  34537. this.zOffset = 0;
  34538. /**
  34539. * Specifies if the material was previously ready
  34540. */
  34541. this._wasPreviouslyReady = false;
  34542. /**
  34543. * Stores the fill mode state
  34544. */
  34545. this._fillMode = Material.TriangleFillMode;
  34546. this.name = name;
  34547. this.id = name || BABYLON.Tools.RandomId();
  34548. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34549. if (this._scene.useRightHandedSystem) {
  34550. this.sideOrientation = Material.ClockWiseSideOrientation;
  34551. }
  34552. else {
  34553. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34554. }
  34555. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34556. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34557. if (!doNotAdd) {
  34558. this._scene.materials.push(this);
  34559. }
  34560. }
  34561. Object.defineProperty(Material, "TriangleFillMode", {
  34562. /**
  34563. * Returns the triangle fill mode
  34564. */
  34565. get: function () {
  34566. return Material._TriangleFillMode;
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(Material, "WireFrameFillMode", {
  34572. /**
  34573. * Returns the wireframe mode
  34574. */
  34575. get: function () {
  34576. return Material._WireFrameFillMode;
  34577. },
  34578. enumerable: true,
  34579. configurable: true
  34580. });
  34581. Object.defineProperty(Material, "PointFillMode", {
  34582. /**
  34583. * Returns the point fill mode
  34584. */
  34585. get: function () {
  34586. return Material._PointFillMode;
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. Object.defineProperty(Material, "PointListDrawMode", {
  34592. /**
  34593. * Returns the point list draw mode
  34594. */
  34595. get: function () {
  34596. return Material._PointListDrawMode;
  34597. },
  34598. enumerable: true,
  34599. configurable: true
  34600. });
  34601. Object.defineProperty(Material, "LineListDrawMode", {
  34602. /**
  34603. * Returns the line list draw mode
  34604. */
  34605. get: function () {
  34606. return Material._LineListDrawMode;
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. Object.defineProperty(Material, "LineLoopDrawMode", {
  34612. /**
  34613. * Returns the line loop draw mode
  34614. */
  34615. get: function () {
  34616. return Material._LineLoopDrawMode;
  34617. },
  34618. enumerable: true,
  34619. configurable: true
  34620. });
  34621. Object.defineProperty(Material, "LineStripDrawMode", {
  34622. /**
  34623. * Returns the line strip draw mode
  34624. */
  34625. get: function () {
  34626. return Material._LineStripDrawMode;
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34632. /**
  34633. * Returns the triangle strip draw mode
  34634. */
  34635. get: function () {
  34636. return Material._TriangleStripDrawMode;
  34637. },
  34638. enumerable: true,
  34639. configurable: true
  34640. });
  34641. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34642. /**
  34643. * Returns the triangle fan draw mode
  34644. */
  34645. get: function () {
  34646. return Material._TriangleFanDrawMode;
  34647. },
  34648. enumerable: true,
  34649. configurable: true
  34650. });
  34651. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34652. /**
  34653. * Returns the clock-wise side orientation
  34654. */
  34655. get: function () {
  34656. return Material._ClockWiseSideOrientation;
  34657. },
  34658. enumerable: true,
  34659. configurable: true
  34660. });
  34661. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34662. /**
  34663. * Returns the counter clock-wise side orientation
  34664. */
  34665. get: function () {
  34666. return Material._CounterClockWiseSideOrientation;
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. Object.defineProperty(Material, "TextureDirtyFlag", {
  34672. /**
  34673. * Returns the dirty texture flag value
  34674. */
  34675. get: function () {
  34676. return Material._TextureDirtyFlag;
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. Object.defineProperty(Material, "LightDirtyFlag", {
  34682. /**
  34683. * Returns the dirty light flag value
  34684. */
  34685. get: function () {
  34686. return Material._LightDirtyFlag;
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34692. /**
  34693. * Returns the dirty fresnel flag value
  34694. */
  34695. get: function () {
  34696. return Material._FresnelDirtyFlag;
  34697. },
  34698. enumerable: true,
  34699. configurable: true
  34700. });
  34701. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34702. /**
  34703. * Returns the dirty attributes flag value
  34704. */
  34705. get: function () {
  34706. return Material._AttributesDirtyFlag;
  34707. },
  34708. enumerable: true,
  34709. configurable: true
  34710. });
  34711. Object.defineProperty(Material, "MiscDirtyFlag", {
  34712. /**
  34713. * Returns the dirty misc flag value
  34714. */
  34715. get: function () {
  34716. return Material._MiscDirtyFlag;
  34717. },
  34718. enumerable: true,
  34719. configurable: true
  34720. });
  34721. Object.defineProperty(Material.prototype, "alpha", {
  34722. /**
  34723. * Gets the alpha value of the material
  34724. */
  34725. get: function () {
  34726. return this._alpha;
  34727. },
  34728. /**
  34729. * Sets the alpha value of the material
  34730. */
  34731. set: function (value) {
  34732. if (this._alpha === value) {
  34733. return;
  34734. }
  34735. this._alpha = value;
  34736. this.markAsDirty(Material.MiscDirtyFlag);
  34737. },
  34738. enumerable: true,
  34739. configurable: true
  34740. });
  34741. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34742. /**
  34743. * Gets the back-face culling state
  34744. */
  34745. get: function () {
  34746. return this._backFaceCulling;
  34747. },
  34748. /**
  34749. * Sets the back-face culling state
  34750. */
  34751. set: function (value) {
  34752. if (this._backFaceCulling === value) {
  34753. return;
  34754. }
  34755. this._backFaceCulling = value;
  34756. this.markAsDirty(Material.TextureDirtyFlag);
  34757. },
  34758. enumerable: true,
  34759. configurable: true
  34760. });
  34761. Object.defineProperty(Material.prototype, "onDispose", {
  34762. /**
  34763. * Called during a dispose event
  34764. */
  34765. set: function (callback) {
  34766. if (this._onDisposeObserver) {
  34767. this.onDisposeObservable.remove(this._onDisposeObserver);
  34768. }
  34769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(Material.prototype, "onBind", {
  34775. /**
  34776. * Called during a bind event
  34777. */
  34778. set: function (callback) {
  34779. if (this._onBindObserver) {
  34780. this.onBindObservable.remove(this._onBindObserver);
  34781. }
  34782. this._onBindObserver = this.onBindObservable.add(callback);
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material.prototype, "alphaMode", {
  34788. /**
  34789. * Gets the value of the alpha mode
  34790. */
  34791. get: function () {
  34792. return this._alphaMode;
  34793. },
  34794. /**
  34795. * Sets the value of the alpha mode.
  34796. *
  34797. * | Value | Type | Description |
  34798. * | --- | --- | --- |
  34799. * | 0 | ALPHA_DISABLE | |
  34800. * | 1 | ALPHA_ADD | |
  34801. * | 2 | ALPHA_COMBINE | |
  34802. * | 3 | ALPHA_SUBTRACT | |
  34803. * | 4 | ALPHA_MULTIPLY | |
  34804. * | 5 | ALPHA_MAXIMIZED | |
  34805. * | 6 | ALPHA_ONEONE | |
  34806. * | 7 | ALPHA_PREMULTIPLIED | |
  34807. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34808. * | 9 | ALPHA_INTERPOLATE | |
  34809. * | 10 | ALPHA_SCREENMODE | |
  34810. *
  34811. */
  34812. set: function (value) {
  34813. if (this._alphaMode === value) {
  34814. return;
  34815. }
  34816. this._alphaMode = value;
  34817. this.markAsDirty(Material.TextureDirtyFlag);
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34823. /**
  34824. * Gets the depth pre-pass value
  34825. */
  34826. get: function () {
  34827. return this._needDepthPrePass;
  34828. },
  34829. /**
  34830. * Sets the need depth pre-pass value
  34831. */
  34832. set: function (value) {
  34833. if (this._needDepthPrePass === value) {
  34834. return;
  34835. }
  34836. this._needDepthPrePass = value;
  34837. if (this._needDepthPrePass) {
  34838. this.checkReadyOnEveryCall = true;
  34839. }
  34840. },
  34841. enumerable: true,
  34842. configurable: true
  34843. });
  34844. Object.defineProperty(Material.prototype, "fogEnabled", {
  34845. /**
  34846. * Gets the value of the fog enabled state
  34847. */
  34848. get: function () {
  34849. return this._fogEnabled;
  34850. },
  34851. /**
  34852. * Sets the state for enabling fog
  34853. */
  34854. set: function (value) {
  34855. if (this._fogEnabled === value) {
  34856. return;
  34857. }
  34858. this._fogEnabled = value;
  34859. this.markAsDirty(Material.MiscDirtyFlag);
  34860. },
  34861. enumerable: true,
  34862. configurable: true
  34863. });
  34864. Object.defineProperty(Material.prototype, "wireframe", {
  34865. /**
  34866. * Gets a value specifying if wireframe mode is enabled
  34867. */
  34868. get: function () {
  34869. switch (this._fillMode) {
  34870. case Material.WireFrameFillMode:
  34871. case Material.LineListDrawMode:
  34872. case Material.LineLoopDrawMode:
  34873. case Material.LineStripDrawMode:
  34874. return true;
  34875. }
  34876. return this._scene.forceWireframe;
  34877. },
  34878. /**
  34879. * Sets the state of wireframe mode
  34880. */
  34881. set: function (value) {
  34882. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(Material.prototype, "pointsCloud", {
  34888. /**
  34889. * Gets the value specifying if point clouds are enabled
  34890. */
  34891. get: function () {
  34892. switch (this._fillMode) {
  34893. case Material.PointFillMode:
  34894. case Material.PointListDrawMode:
  34895. return true;
  34896. }
  34897. return this._scene.forcePointsCloud;
  34898. },
  34899. /**
  34900. * Sets the state of point cloud mode
  34901. */
  34902. set: function (value) {
  34903. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34904. },
  34905. enumerable: true,
  34906. configurable: true
  34907. });
  34908. Object.defineProperty(Material.prototype, "fillMode", {
  34909. /**
  34910. * Gets the material fill mode
  34911. */
  34912. get: function () {
  34913. return this._fillMode;
  34914. },
  34915. /**
  34916. * Sets the material fill mode
  34917. */
  34918. set: function (value) {
  34919. if (this._fillMode === value) {
  34920. return;
  34921. }
  34922. this._fillMode = value;
  34923. this.markAsDirty(Material.MiscDirtyFlag);
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. /**
  34929. * Returns a string representation of the current material
  34930. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34931. * @returns a string with material information
  34932. */
  34933. Material.prototype.toString = function (fullDetails) {
  34934. var ret = "Name: " + this.name;
  34935. if (fullDetails) {
  34936. }
  34937. return ret;
  34938. };
  34939. /**
  34940. * Gets the class name of the material
  34941. * @returns a string with the class name of the material
  34942. */
  34943. Material.prototype.getClassName = function () {
  34944. return "Material";
  34945. };
  34946. Object.defineProperty(Material.prototype, "isFrozen", {
  34947. /**
  34948. * Specifies if updates for the material been locked
  34949. */
  34950. get: function () {
  34951. return this.checkReadyOnlyOnce;
  34952. },
  34953. enumerable: true,
  34954. configurable: true
  34955. });
  34956. /**
  34957. * Locks updates for the material
  34958. */
  34959. Material.prototype.freeze = function () {
  34960. this.checkReadyOnlyOnce = true;
  34961. };
  34962. /**
  34963. * Unlocks updates for the material
  34964. */
  34965. Material.prototype.unfreeze = function () {
  34966. this.checkReadyOnlyOnce = false;
  34967. };
  34968. /**
  34969. * Specifies if the material is ready to be used
  34970. * @param mesh defines the mesh to check
  34971. * @param useInstances specifies if instances should be used
  34972. * @returns a boolean indicating if the material is ready to be used
  34973. */
  34974. Material.prototype.isReady = function (mesh, useInstances) {
  34975. return true;
  34976. };
  34977. /**
  34978. * Specifies that the submesh is ready to be used
  34979. * @param mesh defines the mesh to check
  34980. * @param subMesh defines which submesh to check
  34981. * @param useInstances specifies that instances should be used
  34982. * @returns a boolean indicating that the submesh is ready or not
  34983. */
  34984. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34985. return false;
  34986. };
  34987. /**
  34988. * Returns the material effect
  34989. * @returns the effect associated with the material
  34990. */
  34991. Material.prototype.getEffect = function () {
  34992. return this._effect;
  34993. };
  34994. /**
  34995. * Returns the current scene
  34996. * @returns a Scene
  34997. */
  34998. Material.prototype.getScene = function () {
  34999. return this._scene;
  35000. };
  35001. /**
  35002. * Specifies if the material will require alpha blending
  35003. * @returns a boolean specifying if alpha blending is needed
  35004. */
  35005. Material.prototype.needAlphaBlending = function () {
  35006. return (this.alpha < 1.0);
  35007. };
  35008. /**
  35009. * Specifies if the mesh will require alpha blending
  35010. * @param mesh defines the mesh to check
  35011. * @returns a boolean specifying if alpha blending is needed for the mesh
  35012. */
  35013. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35014. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35015. };
  35016. /**
  35017. * Specifies if this material should be rendered in alpha test mode
  35018. * @returns a boolean specifying if an alpha test is needed.
  35019. */
  35020. Material.prototype.needAlphaTesting = function () {
  35021. return false;
  35022. };
  35023. /**
  35024. * Gets the texture used for the alpha test
  35025. * @returns the texture to use for alpha testing
  35026. */
  35027. Material.prototype.getAlphaTestTexture = function () {
  35028. return null;
  35029. };
  35030. /**
  35031. * Marks the material to indicate that it needs to be re-calculated
  35032. */
  35033. Material.prototype.markDirty = function () {
  35034. this._wasPreviouslyReady = false;
  35035. };
  35036. /** @hidden */
  35037. Material.prototype._preBind = function (effect, overrideOrientation) {
  35038. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35039. var engine = this._scene.getEngine();
  35040. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35041. var reverse = orientation === Material.ClockWiseSideOrientation;
  35042. engine.enableEffect(effect ? effect : this._effect);
  35043. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35044. return reverse;
  35045. };
  35046. /**
  35047. * Binds the material to the mesh
  35048. * @param world defines the world transformation matrix
  35049. * @param mesh defines the mesh to bind the material to
  35050. */
  35051. Material.prototype.bind = function (world, mesh) {
  35052. };
  35053. /**
  35054. * Binds the submesh to the material
  35055. * @param world defines the world transformation matrix
  35056. * @param mesh defines the mesh containing the submesh
  35057. * @param subMesh defines the submesh to bind the material to
  35058. */
  35059. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35060. };
  35061. /**
  35062. * Binds the world matrix to the material
  35063. * @param world defines the world transformation matrix
  35064. */
  35065. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35066. };
  35067. /**
  35068. * Binds the scene's uniform buffer to the effect.
  35069. * @param effect defines the effect to bind to the scene uniform buffer
  35070. * @param sceneUbo defines the uniform buffer storing scene data
  35071. */
  35072. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35073. sceneUbo.bindToEffect(effect, "Scene");
  35074. };
  35075. /**
  35076. * Binds the view matrix to the effect
  35077. * @param effect defines the effect to bind the view matrix to
  35078. */
  35079. Material.prototype.bindView = function (effect) {
  35080. if (!this._useUBO) {
  35081. effect.setMatrix("view", this.getScene().getViewMatrix());
  35082. }
  35083. else {
  35084. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35085. }
  35086. };
  35087. /**
  35088. * Binds the view projection matrix to the effect
  35089. * @param effect defines the effect to bind the view projection matrix to
  35090. */
  35091. Material.prototype.bindViewProjection = function (effect) {
  35092. if (!this._useUBO) {
  35093. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35094. }
  35095. else {
  35096. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35097. }
  35098. };
  35099. /**
  35100. * Specifies if material alpha testing should be turned on for the mesh
  35101. * @param mesh defines the mesh to check
  35102. */
  35103. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35104. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35105. };
  35106. /**
  35107. * Processes to execute after binding the material to a mesh
  35108. * @param mesh defines the rendered mesh
  35109. */
  35110. Material.prototype._afterBind = function (mesh) {
  35111. this._scene._cachedMaterial = this;
  35112. if (mesh) {
  35113. this._scene._cachedVisibility = mesh.visibility;
  35114. }
  35115. else {
  35116. this._scene._cachedVisibility = 1;
  35117. }
  35118. if (mesh) {
  35119. this.onBindObservable.notifyObservers(mesh);
  35120. }
  35121. if (this.disableDepthWrite) {
  35122. var engine = this._scene.getEngine();
  35123. this._cachedDepthWriteState = engine.getDepthWrite();
  35124. engine.setDepthWrite(false);
  35125. }
  35126. };
  35127. /**
  35128. * Unbinds the material from the mesh
  35129. */
  35130. Material.prototype.unbind = function () {
  35131. this.onUnBindObservable.notifyObservers(this);
  35132. if (this.disableDepthWrite) {
  35133. var engine = this._scene.getEngine();
  35134. engine.setDepthWrite(this._cachedDepthWriteState);
  35135. }
  35136. };
  35137. /**
  35138. * Gets the active textures from the material
  35139. * @returns an array of textures
  35140. */
  35141. Material.prototype.getActiveTextures = function () {
  35142. return [];
  35143. };
  35144. /**
  35145. * Specifies if the material uses a texture
  35146. * @param texture defines the texture to check against the material
  35147. * @returns a boolean specifying if the material uses the texture
  35148. */
  35149. Material.prototype.hasTexture = function (texture) {
  35150. return false;
  35151. };
  35152. /**
  35153. * Makes a duplicate of the material, and gives it a new name
  35154. * @param name defines the new name for the duplicated material
  35155. * @returns the cloned material
  35156. */
  35157. Material.prototype.clone = function (name) {
  35158. return null;
  35159. };
  35160. /**
  35161. * Gets the meshes bound to the material
  35162. * @returns an array of meshes bound to the material
  35163. */
  35164. Material.prototype.getBindedMeshes = function () {
  35165. var result = new Array();
  35166. for (var index = 0; index < this._scene.meshes.length; index++) {
  35167. var mesh = this._scene.meshes[index];
  35168. if (mesh.material === this) {
  35169. result.push(mesh);
  35170. }
  35171. }
  35172. return result;
  35173. };
  35174. /**
  35175. * Force shader compilation
  35176. * @param mesh defines the mesh associated with this material
  35177. * @param onCompiled defines a function to execute once the material is compiled
  35178. * @param options defines the options to configure the compilation
  35179. */
  35180. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35181. var _this = this;
  35182. var localOptions = __assign({ clipPlane: false }, options);
  35183. var subMesh = new BABYLON.BaseSubMesh();
  35184. var scene = this.getScene();
  35185. var checkReady = function () {
  35186. if (!_this._scene || !_this._scene.getEngine()) {
  35187. return;
  35188. }
  35189. if (subMesh._materialDefines) {
  35190. subMesh._materialDefines._renderId = -1;
  35191. }
  35192. var clipPlaneState = scene.clipPlane;
  35193. if (localOptions.clipPlane) {
  35194. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35195. }
  35196. if (_this.storeEffectOnSubMeshes) {
  35197. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35198. if (onCompiled) {
  35199. onCompiled(_this);
  35200. }
  35201. }
  35202. else {
  35203. setTimeout(checkReady, 16);
  35204. }
  35205. }
  35206. else {
  35207. if (_this.isReady(mesh)) {
  35208. if (onCompiled) {
  35209. onCompiled(_this);
  35210. }
  35211. }
  35212. else {
  35213. setTimeout(checkReady, 16);
  35214. }
  35215. }
  35216. if (localOptions.clipPlane) {
  35217. scene.clipPlane = clipPlaneState;
  35218. }
  35219. };
  35220. checkReady();
  35221. };
  35222. /**
  35223. * Force shader compilation
  35224. * @param mesh defines the mesh that will use this material
  35225. * @param options defines additional options for compiling the shaders
  35226. * @returns a promise that resolves when the compilation completes
  35227. */
  35228. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35229. var _this = this;
  35230. return new Promise(function (resolve) {
  35231. _this.forceCompilation(mesh, function () {
  35232. resolve();
  35233. }, options);
  35234. });
  35235. };
  35236. /**
  35237. * Marks a define in the material to indicate that it needs to be re-computed
  35238. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35239. */
  35240. Material.prototype.markAsDirty = function (flag) {
  35241. if (flag & Material.TextureDirtyFlag) {
  35242. this._markAllSubMeshesAsTexturesDirty();
  35243. }
  35244. if (flag & Material.LightDirtyFlag) {
  35245. this._markAllSubMeshesAsLightsDirty();
  35246. }
  35247. if (flag & Material.FresnelDirtyFlag) {
  35248. this._markAllSubMeshesAsFresnelDirty();
  35249. }
  35250. if (flag & Material.AttributesDirtyFlag) {
  35251. this._markAllSubMeshesAsAttributesDirty();
  35252. }
  35253. if (flag & Material.MiscDirtyFlag) {
  35254. this._markAllSubMeshesAsMiscDirty();
  35255. }
  35256. this.getScene().resetCachedMaterial();
  35257. };
  35258. /**
  35259. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35260. * @param func defines a function which checks material defines against the submeshes
  35261. */
  35262. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35263. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35264. var mesh = _a[_i];
  35265. if (!mesh.subMeshes) {
  35266. continue;
  35267. }
  35268. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35269. var subMesh = _c[_b];
  35270. if (subMesh.getMaterial() !== this) {
  35271. continue;
  35272. }
  35273. if (!subMesh._materialDefines) {
  35274. continue;
  35275. }
  35276. func(subMesh._materialDefines);
  35277. }
  35278. }
  35279. };
  35280. /**
  35281. * Indicates that image processing needs to be re-calculated for all submeshes
  35282. */
  35283. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35284. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35285. };
  35286. /**
  35287. * Indicates that textures need to be re-calculated for all submeshes
  35288. */
  35289. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35290. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35291. };
  35292. /**
  35293. * Indicates that fresnel needs to be re-calculated for all submeshes
  35294. */
  35295. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35296. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35297. };
  35298. /**
  35299. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35300. */
  35301. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35302. this._markAllSubMeshesAsDirty(function (defines) {
  35303. defines.markAsFresnelDirty();
  35304. defines.markAsMiscDirty();
  35305. });
  35306. };
  35307. /**
  35308. * Indicates that lights need to be re-calculated for all submeshes
  35309. */
  35310. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35311. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35312. };
  35313. /**
  35314. * Indicates that attributes need to be re-calculated for all submeshes
  35315. */
  35316. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35317. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35318. };
  35319. /**
  35320. * Indicates that misc needs to be re-calculated for all submeshes
  35321. */
  35322. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35323. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35324. };
  35325. /**
  35326. * Indicates that textures and misc need to be re-calculated for all submeshes
  35327. */
  35328. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35329. this._markAllSubMeshesAsDirty(function (defines) {
  35330. defines.markAsTexturesDirty();
  35331. defines.markAsMiscDirty();
  35332. });
  35333. };
  35334. /**
  35335. * Disposes the material
  35336. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35337. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35338. */
  35339. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35340. // Animations
  35341. this.getScene().stopAnimation(this);
  35342. this.getScene().freeProcessedMaterials();
  35343. // Remove from scene
  35344. var index = this._scene.materials.indexOf(this);
  35345. if (index >= 0) {
  35346. this._scene.materials.splice(index, 1);
  35347. }
  35348. // Remove from meshes
  35349. for (index = 0; index < this._scene.meshes.length; index++) {
  35350. var mesh = this._scene.meshes[index];
  35351. if (mesh.material === this) {
  35352. mesh.material = null;
  35353. if (mesh.geometry) {
  35354. var geometry = (mesh.geometry);
  35355. if (this.storeEffectOnSubMeshes) {
  35356. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35357. var subMesh = _a[_i];
  35358. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35359. if (forceDisposeEffect && subMesh._materialEffect) {
  35360. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35361. }
  35362. }
  35363. }
  35364. else {
  35365. geometry._releaseVertexArrayObject(this._effect);
  35366. }
  35367. }
  35368. }
  35369. }
  35370. this._uniformBuffer.dispose();
  35371. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35372. if (forceDisposeEffect && this._effect) {
  35373. if (!this.storeEffectOnSubMeshes) {
  35374. this._scene.getEngine()._releaseEffect(this._effect);
  35375. }
  35376. this._effect = null;
  35377. }
  35378. // Callback
  35379. this.onDisposeObservable.notifyObservers(this);
  35380. this.onDisposeObservable.clear();
  35381. this.onBindObservable.clear();
  35382. this.onUnBindObservable.clear();
  35383. };
  35384. /**
  35385. * Serializes this material
  35386. * @returns the serialized material object
  35387. */
  35388. Material.prototype.serialize = function () {
  35389. return BABYLON.SerializationHelper.Serialize(this);
  35390. };
  35391. /**
  35392. * Creates a MultiMaterial from parsed MultiMaterial data.
  35393. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35394. * @param scene defines the hosting scene
  35395. * @returns a new MultiMaterial
  35396. */
  35397. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35398. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35399. multiMaterial.id = parsedMultiMaterial.id;
  35400. if (BABYLON.Tags) {
  35401. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35402. }
  35403. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35404. var subMatId = parsedMultiMaterial.materials[matIndex];
  35405. if (subMatId) {
  35406. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35407. }
  35408. else {
  35409. multiMaterial.subMaterials.push(null);
  35410. }
  35411. }
  35412. return multiMaterial;
  35413. };
  35414. /**
  35415. * Creates a material from parsed material data
  35416. * @param parsedMaterial defines parsed material data
  35417. * @param scene defines the hosting scene
  35418. * @param rootUrl defines the root URL to use to load textures
  35419. * @returns a new material
  35420. */
  35421. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35422. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35423. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35424. }
  35425. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35426. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35427. if (!BABYLON.LegacyPBRMaterial) {
  35428. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35429. return;
  35430. }
  35431. }
  35432. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35433. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35434. };
  35435. // Triangle views
  35436. Material._TriangleFillMode = 0;
  35437. Material._WireFrameFillMode = 1;
  35438. Material._PointFillMode = 2;
  35439. // Draw modes
  35440. Material._PointListDrawMode = 3;
  35441. Material._LineListDrawMode = 4;
  35442. Material._LineLoopDrawMode = 5;
  35443. Material._LineStripDrawMode = 6;
  35444. Material._TriangleStripDrawMode = 7;
  35445. Material._TriangleFanDrawMode = 8;
  35446. /**
  35447. * Stores the clock-wise side orientation
  35448. */
  35449. Material._ClockWiseSideOrientation = 0;
  35450. /**
  35451. * Stores the counter clock-wise side orientation
  35452. */
  35453. Material._CounterClockWiseSideOrientation = 1;
  35454. /**
  35455. * The dirty texture flag value
  35456. */
  35457. Material._TextureDirtyFlag = 1;
  35458. /**
  35459. * The dirty light flag value
  35460. */
  35461. Material._LightDirtyFlag = 2;
  35462. /**
  35463. * The dirty fresnel flag value
  35464. */
  35465. Material._FresnelDirtyFlag = 4;
  35466. /**
  35467. * The dirty attribute flag value
  35468. */
  35469. Material._AttributesDirtyFlag = 8;
  35470. /**
  35471. * The dirty misc flag value
  35472. */
  35473. Material._MiscDirtyFlag = 16;
  35474. __decorate([
  35475. BABYLON.serialize()
  35476. ], Material.prototype, "id", void 0);
  35477. __decorate([
  35478. BABYLON.serialize()
  35479. ], Material.prototype, "name", void 0);
  35480. __decorate([
  35481. BABYLON.serialize()
  35482. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35483. __decorate([
  35484. BABYLON.serialize()
  35485. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35486. __decorate([
  35487. BABYLON.serialize()
  35488. ], Material.prototype, "state", void 0);
  35489. __decorate([
  35490. BABYLON.serialize("alpha")
  35491. ], Material.prototype, "_alpha", void 0);
  35492. __decorate([
  35493. BABYLON.serialize("backFaceCulling")
  35494. ], Material.prototype, "_backFaceCulling", void 0);
  35495. __decorate([
  35496. BABYLON.serialize()
  35497. ], Material.prototype, "sideOrientation", void 0);
  35498. __decorate([
  35499. BABYLON.serialize("alphaMode")
  35500. ], Material.prototype, "_alphaMode", void 0);
  35501. __decorate([
  35502. BABYLON.serialize()
  35503. ], Material.prototype, "_needDepthPrePass", void 0);
  35504. __decorate([
  35505. BABYLON.serialize()
  35506. ], Material.prototype, "disableDepthWrite", void 0);
  35507. __decorate([
  35508. BABYLON.serialize()
  35509. ], Material.prototype, "forceDepthWrite", void 0);
  35510. __decorate([
  35511. BABYLON.serialize()
  35512. ], Material.prototype, "separateCullingPass", void 0);
  35513. __decorate([
  35514. BABYLON.serialize("fogEnabled")
  35515. ], Material.prototype, "_fogEnabled", void 0);
  35516. __decorate([
  35517. BABYLON.serialize()
  35518. ], Material.prototype, "pointSize", void 0);
  35519. __decorate([
  35520. BABYLON.serialize()
  35521. ], Material.prototype, "zOffset", void 0);
  35522. __decorate([
  35523. BABYLON.serialize()
  35524. ], Material.prototype, "wireframe", null);
  35525. __decorate([
  35526. BABYLON.serialize()
  35527. ], Material.prototype, "pointsCloud", null);
  35528. __decorate([
  35529. BABYLON.serialize()
  35530. ], Material.prototype, "fillMode", null);
  35531. return Material;
  35532. }());
  35533. BABYLON.Material = Material;
  35534. })(BABYLON || (BABYLON = {}));
  35535. //# sourceMappingURL=babylon.material.js.map
  35536. var BABYLON;
  35537. (function (BABYLON) {
  35538. var UniformBuffer = /** @class */ (function () {
  35539. /**
  35540. * Uniform buffer objects.
  35541. *
  35542. * Handles blocks of uniform on the GPU.
  35543. *
  35544. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35545. *
  35546. * For more information, please refer to :
  35547. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35548. */
  35549. function UniformBuffer(engine, data, dynamic) {
  35550. this._engine = engine;
  35551. this._noUBO = !engine.supportsUniformBuffers;
  35552. this._dynamic = dynamic;
  35553. this._data = data || [];
  35554. this._uniformLocations = {};
  35555. this._uniformSizes = {};
  35556. this._uniformLocationPointer = 0;
  35557. this._needSync = false;
  35558. if (this._noUBO) {
  35559. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35560. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35561. this.updateFloat = this._updateFloatForEffect;
  35562. this.updateFloat2 = this._updateFloat2ForEffect;
  35563. this.updateFloat3 = this._updateFloat3ForEffect;
  35564. this.updateFloat4 = this._updateFloat4ForEffect;
  35565. this.updateMatrix = this._updateMatrixForEffect;
  35566. this.updateVector3 = this._updateVector3ForEffect;
  35567. this.updateVector4 = this._updateVector4ForEffect;
  35568. this.updateColor3 = this._updateColor3ForEffect;
  35569. this.updateColor4 = this._updateColor4ForEffect;
  35570. }
  35571. else {
  35572. this._engine._uniformBuffers.push(this);
  35573. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35574. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35575. this.updateFloat = this._updateFloatForUniform;
  35576. this.updateFloat2 = this._updateFloat2ForUniform;
  35577. this.updateFloat3 = this._updateFloat3ForUniform;
  35578. this.updateFloat4 = this._updateFloat4ForUniform;
  35579. this.updateMatrix = this._updateMatrixForUniform;
  35580. this.updateVector3 = this._updateVector3ForUniform;
  35581. this.updateVector4 = this._updateVector4ForUniform;
  35582. this.updateColor3 = this._updateColor3ForUniform;
  35583. this.updateColor4 = this._updateColor4ForUniform;
  35584. }
  35585. }
  35586. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35587. // Properties
  35588. /**
  35589. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35590. * or just falling back on setUniformXXX calls.
  35591. */
  35592. get: function () {
  35593. return !this._noUBO;
  35594. },
  35595. enumerable: true,
  35596. configurable: true
  35597. });
  35598. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35599. /**
  35600. * Indicates if the WebGL underlying uniform buffer is in sync
  35601. * with the javascript cache data.
  35602. */
  35603. get: function () {
  35604. return !this._needSync;
  35605. },
  35606. enumerable: true,
  35607. configurable: true
  35608. });
  35609. /**
  35610. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35611. * Also, a dynamic UniformBuffer will disable cache verification and always
  35612. * update the underlying WebGL uniform buffer to the GPU.
  35613. */
  35614. UniformBuffer.prototype.isDynamic = function () {
  35615. return this._dynamic !== undefined;
  35616. };
  35617. /**
  35618. * The data cache on JS side.
  35619. */
  35620. UniformBuffer.prototype.getData = function () {
  35621. return this._bufferData;
  35622. };
  35623. /**
  35624. * The underlying WebGL Uniform buffer.
  35625. */
  35626. UniformBuffer.prototype.getBuffer = function () {
  35627. return this._buffer;
  35628. };
  35629. /**
  35630. * std140 layout specifies how to align data within an UBO structure.
  35631. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35632. * for specs.
  35633. */
  35634. UniformBuffer.prototype._fillAlignment = function (size) {
  35635. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35636. // and 4x4 matrices
  35637. // TODO : change if other types are used
  35638. var alignment;
  35639. if (size <= 2) {
  35640. alignment = size;
  35641. }
  35642. else {
  35643. alignment = 4;
  35644. }
  35645. if ((this._uniformLocationPointer % alignment) !== 0) {
  35646. var oldPointer = this._uniformLocationPointer;
  35647. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35648. var diff = this._uniformLocationPointer - oldPointer;
  35649. for (var i = 0; i < diff; i++) {
  35650. this._data.push(0);
  35651. }
  35652. }
  35653. };
  35654. /**
  35655. * Adds an uniform in the buffer.
  35656. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35657. * for the layout to be correct !
  35658. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35659. * @param {number|number[]} size Data size, or data directly.
  35660. */
  35661. UniformBuffer.prototype.addUniform = function (name, size) {
  35662. if (this._noUBO) {
  35663. return;
  35664. }
  35665. if (this._uniformLocations[name] !== undefined) {
  35666. // Already existing uniform
  35667. return;
  35668. }
  35669. // This function must be called in the order of the shader layout !
  35670. // size can be the size of the uniform, or data directly
  35671. var data;
  35672. if (size instanceof Array) {
  35673. data = size;
  35674. size = data.length;
  35675. }
  35676. else {
  35677. size = size;
  35678. data = [];
  35679. // Fill with zeros
  35680. for (var i = 0; i < size; i++) {
  35681. data.push(0);
  35682. }
  35683. }
  35684. this._fillAlignment(size);
  35685. this._uniformSizes[name] = size;
  35686. this._uniformLocations[name] = this._uniformLocationPointer;
  35687. this._uniformLocationPointer += size;
  35688. for (var i = 0; i < size; i++) {
  35689. this._data.push(data[i]);
  35690. }
  35691. this._needSync = true;
  35692. };
  35693. /**
  35694. * Wrapper for addUniform.
  35695. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35696. * @param {Matrix} mat A 4x4 matrix.
  35697. */
  35698. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35699. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35700. };
  35701. /**
  35702. * Wrapper for addUniform.
  35703. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35704. * @param {number} x
  35705. * @param {number} y
  35706. */
  35707. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35708. var temp = [x, y];
  35709. this.addUniform(name, temp);
  35710. };
  35711. /**
  35712. * Wrapper for addUniform.
  35713. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35714. * @param {number} x
  35715. * @param {number} y
  35716. * @param {number} z
  35717. */
  35718. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35719. var temp = [x, y, z];
  35720. this.addUniform(name, temp);
  35721. };
  35722. /**
  35723. * Wrapper for addUniform.
  35724. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35725. * @param {Color3} color
  35726. */
  35727. UniformBuffer.prototype.addColor3 = function (name, color) {
  35728. var temp = new Array();
  35729. color.toArray(temp);
  35730. this.addUniform(name, temp);
  35731. };
  35732. /**
  35733. * Wrapper for addUniform.
  35734. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35735. * @param {Color3} color
  35736. * @param {number} alpha
  35737. */
  35738. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35739. var temp = new Array();
  35740. color.toArray(temp);
  35741. temp.push(alpha);
  35742. this.addUniform(name, temp);
  35743. };
  35744. /**
  35745. * Wrapper for addUniform.
  35746. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35747. * @param {Vector3} vector
  35748. */
  35749. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35750. var temp = new Array();
  35751. vector.toArray(temp);
  35752. this.addUniform(name, temp);
  35753. };
  35754. /**
  35755. * Wrapper for addUniform.
  35756. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35757. */
  35758. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35759. this.addUniform(name, 12);
  35760. };
  35761. /**
  35762. * Wrapper for addUniform.
  35763. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35764. */
  35765. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35766. this.addUniform(name, 8);
  35767. };
  35768. /**
  35769. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35770. */
  35771. UniformBuffer.prototype.create = function () {
  35772. if (this._noUBO) {
  35773. return;
  35774. }
  35775. if (this._buffer) {
  35776. return; // nothing to do
  35777. }
  35778. // See spec, alignment must be filled as a vec4
  35779. this._fillAlignment(4);
  35780. this._bufferData = new Float32Array(this._data);
  35781. this._rebuild();
  35782. this._needSync = true;
  35783. };
  35784. UniformBuffer.prototype._rebuild = function () {
  35785. if (this._noUBO) {
  35786. return;
  35787. }
  35788. if (this._dynamic) {
  35789. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35790. }
  35791. else {
  35792. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35793. }
  35794. };
  35795. /**
  35796. * Updates the WebGL Uniform Buffer on the GPU.
  35797. * If the `dynamic` flag is set to true, no cache comparison is done.
  35798. * Otherwise, the buffer will be updated only if the cache differs.
  35799. */
  35800. UniformBuffer.prototype.update = function () {
  35801. if (!this._buffer) {
  35802. this.create();
  35803. return;
  35804. }
  35805. if (!this._dynamic && !this._needSync) {
  35806. return;
  35807. }
  35808. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35809. this._needSync = false;
  35810. };
  35811. /**
  35812. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35813. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35814. * @param {number[]|Float32Array} data Flattened data
  35815. * @param {number} size Size of the data.
  35816. */
  35817. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35818. var location = this._uniformLocations[uniformName];
  35819. if (location === undefined) {
  35820. if (this._buffer) {
  35821. // Cannot add an uniform if the buffer is already created
  35822. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35823. return;
  35824. }
  35825. this.addUniform(uniformName, size);
  35826. location = this._uniformLocations[uniformName];
  35827. }
  35828. if (!this._buffer) {
  35829. this.create();
  35830. }
  35831. if (!this._dynamic) {
  35832. // Cache for static uniform buffers
  35833. var changed = false;
  35834. for (var i = 0; i < size; i++) {
  35835. if (this._bufferData[location + i] !== data[i]) {
  35836. changed = true;
  35837. this._bufferData[location + i] = data[i];
  35838. }
  35839. }
  35840. this._needSync = this._needSync || changed;
  35841. }
  35842. else {
  35843. // No cache for dynamic
  35844. for (var i = 0; i < size; i++) {
  35845. this._bufferData[location + i] = data[i];
  35846. }
  35847. }
  35848. };
  35849. // Update methods
  35850. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35851. // To match std140, matrix must be realigned
  35852. for (var i = 0; i < 3; i++) {
  35853. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35854. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35855. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35856. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35857. }
  35858. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35859. };
  35860. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35861. this._currentEffect.setMatrix3x3(name, matrix);
  35862. };
  35863. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35864. this._currentEffect.setMatrix2x2(name, matrix);
  35865. };
  35866. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35867. // To match std140, matrix must be realigned
  35868. for (var i = 0; i < 2; i++) {
  35869. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35870. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35871. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35872. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35873. }
  35874. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35875. };
  35876. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35877. this._currentEffect.setFloat(name, x);
  35878. };
  35879. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35880. UniformBuffer._tempBuffer[0] = x;
  35881. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35882. };
  35883. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35884. if (suffix === void 0) { suffix = ""; }
  35885. this._currentEffect.setFloat2(name + suffix, x, y);
  35886. };
  35887. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35888. if (suffix === void 0) { suffix = ""; }
  35889. UniformBuffer._tempBuffer[0] = x;
  35890. UniformBuffer._tempBuffer[1] = y;
  35891. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35892. };
  35893. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35894. if (suffix === void 0) { suffix = ""; }
  35895. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35896. };
  35897. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35898. if (suffix === void 0) { suffix = ""; }
  35899. UniformBuffer._tempBuffer[0] = x;
  35900. UniformBuffer._tempBuffer[1] = y;
  35901. UniformBuffer._tempBuffer[2] = z;
  35902. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35903. };
  35904. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35905. if (suffix === void 0) { suffix = ""; }
  35906. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35907. };
  35908. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35909. if (suffix === void 0) { suffix = ""; }
  35910. UniformBuffer._tempBuffer[0] = x;
  35911. UniformBuffer._tempBuffer[1] = y;
  35912. UniformBuffer._tempBuffer[2] = z;
  35913. UniformBuffer._tempBuffer[3] = w;
  35914. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35915. };
  35916. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35917. this._currentEffect.setMatrix(name, mat);
  35918. };
  35919. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35920. this.updateUniform(name, mat.toArray(), 16);
  35921. };
  35922. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35923. this._currentEffect.setVector3(name, vector);
  35924. };
  35925. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35926. vector.toArray(UniformBuffer._tempBuffer);
  35927. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35928. };
  35929. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35930. this._currentEffect.setVector4(name, vector);
  35931. };
  35932. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35933. vector.toArray(UniformBuffer._tempBuffer);
  35934. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35935. };
  35936. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35937. if (suffix === void 0) { suffix = ""; }
  35938. this._currentEffect.setColor3(name + suffix, color);
  35939. };
  35940. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35941. if (suffix === void 0) { suffix = ""; }
  35942. color.toArray(UniformBuffer._tempBuffer);
  35943. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35944. };
  35945. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35946. if (suffix === void 0) { suffix = ""; }
  35947. this._currentEffect.setColor4(name + suffix, color, alpha);
  35948. };
  35949. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35950. if (suffix === void 0) { suffix = ""; }
  35951. color.toArray(UniformBuffer._tempBuffer);
  35952. UniformBuffer._tempBuffer[3] = alpha;
  35953. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35954. };
  35955. /**
  35956. * Sets a sampler uniform on the effect.
  35957. * @param {string} name Name of the sampler.
  35958. * @param {Texture} texture
  35959. */
  35960. UniformBuffer.prototype.setTexture = function (name, texture) {
  35961. this._currentEffect.setTexture(name, texture);
  35962. };
  35963. /**
  35964. * Directly updates the value of the uniform in the cache AND on the GPU.
  35965. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35966. * @param {number[]|Float32Array} data Flattened data
  35967. */
  35968. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35969. this.updateUniform(uniformName, data, data.length);
  35970. this.update();
  35971. };
  35972. /**
  35973. * Binds this uniform buffer to an effect.
  35974. * @param {Effect} effect
  35975. * @param {string} name Name of the uniform block in the shader.
  35976. */
  35977. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35978. this._currentEffect = effect;
  35979. if (this._noUBO || !this._buffer) {
  35980. return;
  35981. }
  35982. effect.bindUniformBuffer(this._buffer, name);
  35983. };
  35984. /**
  35985. * Disposes the uniform buffer.
  35986. */
  35987. UniformBuffer.prototype.dispose = function () {
  35988. if (this._noUBO) {
  35989. return;
  35990. }
  35991. var index = this._engine._uniformBuffers.indexOf(this);
  35992. if (index !== -1) {
  35993. this._engine._uniformBuffers.splice(index, 1);
  35994. }
  35995. if (!this._buffer) {
  35996. return;
  35997. }
  35998. if (this._engine._releaseBuffer(this._buffer)) {
  35999. this._buffer = null;
  36000. }
  36001. };
  36002. // Pool for avoiding memory leaks
  36003. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36004. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36005. return UniformBuffer;
  36006. }());
  36007. BABYLON.UniformBuffer = UniformBuffer;
  36008. })(BABYLON || (BABYLON = {}));
  36009. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36010. var BABYLON;
  36011. (function (BABYLON) {
  36012. /**
  36013. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36014. */
  36015. var VertexData = /** @class */ (function () {
  36016. function VertexData() {
  36017. }
  36018. /**
  36019. * Uses the passed data array to set the set the values for the specified kind of data
  36020. * @param data a linear array of floating numbers
  36021. * @param kind the type of data that is being set, eg positions, colors etc
  36022. */
  36023. VertexData.prototype.set = function (data, kind) {
  36024. switch (kind) {
  36025. case BABYLON.VertexBuffer.PositionKind:
  36026. this.positions = data;
  36027. break;
  36028. case BABYLON.VertexBuffer.NormalKind:
  36029. this.normals = data;
  36030. break;
  36031. case BABYLON.VertexBuffer.TangentKind:
  36032. this.tangents = data;
  36033. break;
  36034. case BABYLON.VertexBuffer.UVKind:
  36035. this.uvs = data;
  36036. break;
  36037. case BABYLON.VertexBuffer.UV2Kind:
  36038. this.uvs2 = data;
  36039. break;
  36040. case BABYLON.VertexBuffer.UV3Kind:
  36041. this.uvs3 = data;
  36042. break;
  36043. case BABYLON.VertexBuffer.UV4Kind:
  36044. this.uvs4 = data;
  36045. break;
  36046. case BABYLON.VertexBuffer.UV5Kind:
  36047. this.uvs5 = data;
  36048. break;
  36049. case BABYLON.VertexBuffer.UV6Kind:
  36050. this.uvs6 = data;
  36051. break;
  36052. case BABYLON.VertexBuffer.ColorKind:
  36053. this.colors = data;
  36054. break;
  36055. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36056. this.matricesIndices = data;
  36057. break;
  36058. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36059. this.matricesWeights = data;
  36060. break;
  36061. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36062. this.matricesIndicesExtra = data;
  36063. break;
  36064. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36065. this.matricesWeightsExtra = data;
  36066. break;
  36067. }
  36068. };
  36069. /**
  36070. * Associates the vertexData to the passed Mesh.
  36071. * Sets it as updatable or not (default `false`)
  36072. * @param mesh the mesh the vertexData is applied to
  36073. * @param updatable when used and having the value true allows new data to update the vertexData
  36074. * @returns the VertexData
  36075. */
  36076. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36077. this._applyTo(mesh, updatable);
  36078. return this;
  36079. };
  36080. /**
  36081. * Associates the vertexData to the passed Geometry.
  36082. * Sets it as updatable or not (default `false`)
  36083. * @param geometry the geometry the vertexData is applied to
  36084. * @param updatable when used and having the value true allows new data to update the vertexData
  36085. * @returns VertexData
  36086. */
  36087. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36088. this._applyTo(geometry, updatable);
  36089. return this;
  36090. };
  36091. /**
  36092. * Updates the associated mesh
  36093. * @param mesh the mesh to be updated
  36094. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36095. * @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
  36096. * @returns VertexData
  36097. */
  36098. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36099. this._update(mesh);
  36100. return this;
  36101. };
  36102. /**
  36103. * Updates the associated geometry
  36104. * @param geometry the geometry to be updated
  36105. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36106. * @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
  36107. * @returns VertexData.
  36108. */
  36109. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36110. this._update(geometry);
  36111. return this;
  36112. };
  36113. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36114. if (updatable === void 0) { updatable = false; }
  36115. if (this.positions) {
  36116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36117. }
  36118. if (this.normals) {
  36119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36120. }
  36121. if (this.tangents) {
  36122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36123. }
  36124. if (this.uvs) {
  36125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36126. }
  36127. if (this.uvs2) {
  36128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36129. }
  36130. if (this.uvs3) {
  36131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36132. }
  36133. if (this.uvs4) {
  36134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36135. }
  36136. if (this.uvs5) {
  36137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36138. }
  36139. if (this.uvs6) {
  36140. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36141. }
  36142. if (this.colors) {
  36143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36144. }
  36145. if (this.matricesIndices) {
  36146. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36147. }
  36148. if (this.matricesWeights) {
  36149. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36150. }
  36151. if (this.matricesIndicesExtra) {
  36152. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36153. }
  36154. if (this.matricesWeightsExtra) {
  36155. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36156. }
  36157. if (this.indices) {
  36158. meshOrGeometry.setIndices(this.indices, null, updatable);
  36159. }
  36160. return this;
  36161. };
  36162. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36163. if (this.positions) {
  36164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36165. }
  36166. if (this.normals) {
  36167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36168. }
  36169. if (this.tangents) {
  36170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36171. }
  36172. if (this.uvs) {
  36173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36174. }
  36175. if (this.uvs2) {
  36176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36177. }
  36178. if (this.uvs3) {
  36179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36180. }
  36181. if (this.uvs4) {
  36182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36183. }
  36184. if (this.uvs5) {
  36185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36186. }
  36187. if (this.uvs6) {
  36188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36189. }
  36190. if (this.colors) {
  36191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36192. }
  36193. if (this.matricesIndices) {
  36194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36195. }
  36196. if (this.matricesWeights) {
  36197. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36198. }
  36199. if (this.matricesIndicesExtra) {
  36200. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36201. }
  36202. if (this.matricesWeightsExtra) {
  36203. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36204. }
  36205. if (this.indices) {
  36206. meshOrGeometry.setIndices(this.indices, null);
  36207. }
  36208. return this;
  36209. };
  36210. /**
  36211. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36212. * @param matrix the transforming matrix
  36213. * @returns the VertexData
  36214. */
  36215. VertexData.prototype.transform = function (matrix) {
  36216. var transformed = BABYLON.Vector3.Zero();
  36217. var index;
  36218. if (this.positions) {
  36219. var position = BABYLON.Vector3.Zero();
  36220. for (index = 0; index < this.positions.length; index += 3) {
  36221. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36222. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36223. this.positions[index] = transformed.x;
  36224. this.positions[index + 1] = transformed.y;
  36225. this.positions[index + 2] = transformed.z;
  36226. }
  36227. }
  36228. if (this.normals) {
  36229. var normal = BABYLON.Vector3.Zero();
  36230. for (index = 0; index < this.normals.length; index += 3) {
  36231. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36232. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36233. this.normals[index] = transformed.x;
  36234. this.normals[index + 1] = transformed.y;
  36235. this.normals[index + 2] = transformed.z;
  36236. }
  36237. }
  36238. if (this.tangents) {
  36239. var tangent = BABYLON.Vector4.Zero();
  36240. var tangentTransformed = BABYLON.Vector4.Zero();
  36241. for (index = 0; index < this.tangents.length; index += 4) {
  36242. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36243. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36244. this.tangents[index] = tangentTransformed.x;
  36245. this.tangents[index + 1] = tangentTransformed.y;
  36246. this.tangents[index + 2] = tangentTransformed.z;
  36247. this.tangents[index + 3] = tangentTransformed.w;
  36248. }
  36249. }
  36250. return this;
  36251. };
  36252. /**
  36253. * Merges the passed VertexData into the current one
  36254. * @param other the VertexData to be merged into the current one
  36255. * @returns the modified VertexData
  36256. */
  36257. VertexData.prototype.merge = function (other) {
  36258. this._validate();
  36259. other._validate();
  36260. if (!this.normals !== !other.normals ||
  36261. !this.tangents !== !other.tangents ||
  36262. !this.uvs !== !other.uvs ||
  36263. !this.uvs2 !== !other.uvs2 ||
  36264. !this.uvs3 !== !other.uvs3 ||
  36265. !this.uvs4 !== !other.uvs4 ||
  36266. !this.uvs5 !== !other.uvs5 ||
  36267. !this.uvs6 !== !other.uvs6 ||
  36268. !this.colors !== !other.colors ||
  36269. !this.matricesIndices !== !other.matricesIndices ||
  36270. !this.matricesWeights !== !other.matricesWeights ||
  36271. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36272. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36273. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36274. }
  36275. if (other.indices) {
  36276. if (!this.indices) {
  36277. this.indices = [];
  36278. }
  36279. var offset = this.positions ? this.positions.length / 3 : 0;
  36280. for (var index = 0; index < other.indices.length; index++) {
  36281. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36282. this.indices.push(other.indices[index] + offset);
  36283. }
  36284. }
  36285. this.positions = this._mergeElement(this.positions, other.positions);
  36286. this.normals = this._mergeElement(this.normals, other.normals);
  36287. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36288. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36289. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36290. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36291. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36292. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36293. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36294. this.colors = this._mergeElement(this.colors, other.colors);
  36295. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36296. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36297. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36298. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36299. return this;
  36300. };
  36301. VertexData.prototype._mergeElement = function (source, other) {
  36302. if (!source) {
  36303. return other;
  36304. }
  36305. if (!other) {
  36306. return source;
  36307. }
  36308. var len = other.length + source.length;
  36309. var isSrcTypedArray = source instanceof Float32Array;
  36310. var isOthTypedArray = other instanceof Float32Array;
  36311. // use non-loop method when the source is Float32Array
  36312. if (isSrcTypedArray) {
  36313. var ret32 = new Float32Array(len);
  36314. ret32.set(source);
  36315. ret32.set(other, source.length);
  36316. return ret32;
  36317. // source is number[], when other is also use concat
  36318. }
  36319. else if (!isOthTypedArray) {
  36320. return source.concat(other);
  36321. // source is a number[], but other is a Float32Array, loop required
  36322. }
  36323. else {
  36324. var ret = source.slice(0); // copy source to a separate array
  36325. for (var i = 0, len = other.length; i < len; i++) {
  36326. ret.push(other[i]);
  36327. }
  36328. return ret;
  36329. }
  36330. };
  36331. VertexData.prototype._validate = function () {
  36332. if (!this.positions) {
  36333. throw new Error("Positions are required");
  36334. }
  36335. var getElementCount = function (kind, values) {
  36336. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36337. if ((values.length % stride) !== 0) {
  36338. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36339. }
  36340. return values.length / stride;
  36341. };
  36342. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36343. var validateElementCount = function (kind, values) {
  36344. var elementCount = getElementCount(kind, values);
  36345. if (elementCount !== positionsElementCount) {
  36346. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36347. }
  36348. };
  36349. if (this.normals)
  36350. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36351. if (this.tangents)
  36352. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36353. if (this.uvs)
  36354. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36355. if (this.uvs2)
  36356. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36357. if (this.uvs3)
  36358. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36359. if (this.uvs4)
  36360. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36361. if (this.uvs5)
  36362. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36363. if (this.uvs6)
  36364. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36365. if (this.colors)
  36366. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36367. if (this.matricesIndices)
  36368. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36369. if (this.matricesWeights)
  36370. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36371. if (this.matricesIndicesExtra)
  36372. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36373. if (this.matricesWeightsExtra)
  36374. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36375. };
  36376. /**
  36377. * Serializes the VertexData
  36378. * @returns a serialized object
  36379. */
  36380. VertexData.prototype.serialize = function () {
  36381. var serializationObject = this.serialize();
  36382. if (this.positions) {
  36383. serializationObject.positions = this.positions;
  36384. }
  36385. if (this.normals) {
  36386. serializationObject.normals = this.normals;
  36387. }
  36388. if (this.tangents) {
  36389. serializationObject.tangents = this.tangents;
  36390. }
  36391. if (this.uvs) {
  36392. serializationObject.uvs = this.uvs;
  36393. }
  36394. if (this.uvs2) {
  36395. serializationObject.uvs2 = this.uvs2;
  36396. }
  36397. if (this.uvs3) {
  36398. serializationObject.uvs3 = this.uvs3;
  36399. }
  36400. if (this.uvs4) {
  36401. serializationObject.uvs4 = this.uvs4;
  36402. }
  36403. if (this.uvs5) {
  36404. serializationObject.uvs5 = this.uvs5;
  36405. }
  36406. if (this.uvs6) {
  36407. serializationObject.uvs6 = this.uvs6;
  36408. }
  36409. if (this.colors) {
  36410. serializationObject.colors = this.colors;
  36411. }
  36412. if (this.matricesIndices) {
  36413. serializationObject.matricesIndices = this.matricesIndices;
  36414. serializationObject.matricesIndices._isExpanded = true;
  36415. }
  36416. if (this.matricesWeights) {
  36417. serializationObject.matricesWeights = this.matricesWeights;
  36418. }
  36419. if (this.matricesIndicesExtra) {
  36420. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36421. serializationObject.matricesIndicesExtra._isExpanded = true;
  36422. }
  36423. if (this.matricesWeightsExtra) {
  36424. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36425. }
  36426. serializationObject.indices = this.indices;
  36427. return serializationObject;
  36428. };
  36429. // Statics
  36430. /**
  36431. * Extracts the vertexData from a mesh
  36432. * @param mesh the mesh from which to extract the VertexData
  36433. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36434. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36435. * @returns the object VertexData associated to the passed mesh
  36436. */
  36437. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36438. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36439. };
  36440. /**
  36441. * Extracts the vertexData from the geometry
  36442. * @param geometry the geometry from which to extract the VertexData
  36443. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36444. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36445. * @returns the object VertexData associated to the passed mesh
  36446. */
  36447. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36448. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36449. };
  36450. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36451. var result = new VertexData();
  36452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36453. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36454. }
  36455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36456. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36457. }
  36458. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36459. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36460. }
  36461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36462. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36463. }
  36464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36465. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36466. }
  36467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36468. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36469. }
  36470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36471. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36472. }
  36473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36474. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36475. }
  36476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36477. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36478. }
  36479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36480. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36481. }
  36482. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36483. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36484. }
  36485. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36486. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36487. }
  36488. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36489. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36490. }
  36491. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36492. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36493. }
  36494. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36495. return result;
  36496. };
  36497. /**
  36498. * Creates the VertexData for a Ribbon
  36499. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36500. * * pathArray array of paths, each of which an array of successive Vector3
  36501. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36502. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36503. * * 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
  36504. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36505. * * 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)
  36506. * * 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)
  36507. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36508. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36509. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36510. * @returns the VertexData of the ribbon
  36511. */
  36512. VertexData.CreateRibbon = function (options) {
  36513. var pathArray = options.pathArray;
  36514. var closeArray = options.closeArray || false;
  36515. var closePath = options.closePath || false;
  36516. var invertUV = options.invertUV || false;
  36517. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36518. var offset = options.offset || defaultOffset;
  36519. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36520. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36521. var customUV = options.uvs;
  36522. var customColors = options.colors;
  36523. var positions = [];
  36524. var indices = [];
  36525. var normals = [];
  36526. var uvs = [];
  36527. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36528. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36529. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36530. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36531. var minlg; // minimal length among all paths from pathArray
  36532. var lg = []; // array of path lengths : nb of vertex per path
  36533. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36534. var p; // path iterator
  36535. var i; // point iterator
  36536. var j; // point iterator
  36537. // if single path in pathArray
  36538. if (pathArray.length < 2) {
  36539. var ar1 = [];
  36540. var ar2 = [];
  36541. for (i = 0; i < pathArray[0].length - offset; i++) {
  36542. ar1.push(pathArray[0][i]);
  36543. ar2.push(pathArray[0][i + offset]);
  36544. }
  36545. pathArray = [ar1, ar2];
  36546. }
  36547. // positions and horizontal distances (u)
  36548. var idc = 0;
  36549. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36550. var path;
  36551. var l;
  36552. minlg = pathArray[0].length;
  36553. var vectlg;
  36554. var dist;
  36555. for (p = 0; p < pathArray.length; p++) {
  36556. uTotalDistance[p] = 0;
  36557. us[p] = [0];
  36558. path = pathArray[p];
  36559. l = path.length;
  36560. minlg = (minlg < l) ? minlg : l;
  36561. j = 0;
  36562. while (j < l) {
  36563. positions.push(path[j].x, path[j].y, path[j].z);
  36564. if (j > 0) {
  36565. vectlg = path[j].subtract(path[j - 1]).length();
  36566. dist = vectlg + uTotalDistance[p];
  36567. us[p].push(dist);
  36568. uTotalDistance[p] = dist;
  36569. }
  36570. j++;
  36571. }
  36572. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36573. j--;
  36574. positions.push(path[0].x, path[0].y, path[0].z);
  36575. vectlg = path[j].subtract(path[0]).length();
  36576. dist = vectlg + uTotalDistance[p];
  36577. us[p].push(dist);
  36578. uTotalDistance[p] = dist;
  36579. }
  36580. lg[p] = l + closePathCorr;
  36581. idx[p] = idc;
  36582. idc += (l + closePathCorr);
  36583. }
  36584. // vertical distances (v)
  36585. var path1;
  36586. var path2;
  36587. var vertex1 = null;
  36588. var vertex2 = null;
  36589. for (i = 0; i < minlg + closePathCorr; i++) {
  36590. vTotalDistance[i] = 0;
  36591. vs[i] = [0];
  36592. for (p = 0; p < pathArray.length - 1; p++) {
  36593. path1 = pathArray[p];
  36594. path2 = pathArray[p + 1];
  36595. if (i === minlg) { // closePath
  36596. vertex1 = path1[0];
  36597. vertex2 = path2[0];
  36598. }
  36599. else {
  36600. vertex1 = path1[i];
  36601. vertex2 = path2[i];
  36602. }
  36603. vectlg = vertex2.subtract(vertex1).length();
  36604. dist = vectlg + vTotalDistance[i];
  36605. vs[i].push(dist);
  36606. vTotalDistance[i] = dist;
  36607. }
  36608. if (closeArray && vertex2 && vertex1) {
  36609. path1 = pathArray[p];
  36610. path2 = pathArray[0];
  36611. if (i === minlg) { // closePath
  36612. vertex2 = path2[0];
  36613. }
  36614. vectlg = vertex2.subtract(vertex1).length();
  36615. dist = vectlg + vTotalDistance[i];
  36616. vTotalDistance[i] = dist;
  36617. }
  36618. }
  36619. // uvs
  36620. var u;
  36621. var v;
  36622. if (customUV) {
  36623. for (p = 0; p < customUV.length; p++) {
  36624. uvs.push(customUV[p].x, customUV[p].y);
  36625. }
  36626. }
  36627. else {
  36628. for (p = 0; p < pathArray.length; p++) {
  36629. for (i = 0; i < minlg + closePathCorr; i++) {
  36630. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36631. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36632. if (invertUV) {
  36633. uvs.push(v, u);
  36634. }
  36635. else {
  36636. uvs.push(u, v);
  36637. }
  36638. }
  36639. }
  36640. }
  36641. // indices
  36642. p = 0; // path index
  36643. var pi = 0; // positions array index
  36644. var l1 = lg[p] - 1; // path1 length
  36645. var l2 = lg[p + 1] - 1; // path2 length
  36646. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36647. var shft = idx[1] - idx[0]; // shift
  36648. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36649. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36650. // 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
  36651. indices.push(pi, pi + shft, pi + 1);
  36652. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36653. pi += 1;
  36654. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36655. p++;
  36656. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36657. shft = idx[0] - idx[p];
  36658. l1 = lg[p] - 1;
  36659. l2 = lg[0] - 1;
  36660. }
  36661. else {
  36662. shft = idx[p + 1] - idx[p];
  36663. l1 = lg[p] - 1;
  36664. l2 = lg[p + 1] - 1;
  36665. }
  36666. pi = idx[p];
  36667. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36668. }
  36669. }
  36670. // normals
  36671. VertexData.ComputeNormals(positions, indices, normals);
  36672. if (closePath) { // update both the first and last vertex normals to their average value
  36673. var indexFirst = 0;
  36674. var indexLast = 0;
  36675. for (p = 0; p < pathArray.length; p++) {
  36676. indexFirst = idx[p] * 3;
  36677. if (p + 1 < pathArray.length) {
  36678. indexLast = (idx[p + 1] - 1) * 3;
  36679. }
  36680. else {
  36681. indexLast = normals.length - 3;
  36682. }
  36683. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36684. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36685. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36686. normals[indexLast] = normals[indexFirst];
  36687. normals[indexLast + 1] = normals[indexFirst + 1];
  36688. normals[indexLast + 2] = normals[indexFirst + 2];
  36689. }
  36690. }
  36691. // sides
  36692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36693. // Colors
  36694. var colors = null;
  36695. if (customColors) {
  36696. colors = new Float32Array(customColors.length * 4);
  36697. for (var c = 0; c < customColors.length; c++) {
  36698. colors[c * 4] = customColors[c].r;
  36699. colors[c * 4 + 1] = customColors[c].g;
  36700. colors[c * 4 + 2] = customColors[c].b;
  36701. colors[c * 4 + 3] = customColors[c].a;
  36702. }
  36703. }
  36704. // Result
  36705. var vertexData = new VertexData();
  36706. var positions32 = new Float32Array(positions);
  36707. var normals32 = new Float32Array(normals);
  36708. var uvs32 = new Float32Array(uvs);
  36709. vertexData.indices = indices;
  36710. vertexData.positions = positions32;
  36711. vertexData.normals = normals32;
  36712. vertexData.uvs = uvs32;
  36713. if (colors) {
  36714. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36715. }
  36716. if (closePath) {
  36717. vertexData._idx = idx;
  36718. }
  36719. return vertexData;
  36720. };
  36721. /**
  36722. * Creates the VertexData for a box
  36723. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36724. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36725. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36726. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36727. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36728. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36729. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36730. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36731. * * 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)
  36732. * * 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)
  36733. * @returns the VertexData of the box
  36734. */
  36735. VertexData.CreateBox = function (options) {
  36736. var normalsSource = [
  36737. new BABYLON.Vector3(0, 0, 1),
  36738. new BABYLON.Vector3(0, 0, -1),
  36739. new BABYLON.Vector3(1, 0, 0),
  36740. new BABYLON.Vector3(-1, 0, 0),
  36741. new BABYLON.Vector3(0, 1, 0),
  36742. new BABYLON.Vector3(0, -1, 0)
  36743. ];
  36744. var indices = [];
  36745. var positions = [];
  36746. var normals = [];
  36747. var uvs = [];
  36748. var width = options.width || options.size || 1;
  36749. var height = options.height || options.size || 1;
  36750. var depth = options.depth || options.size || 1;
  36751. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36752. var faceUV = options.faceUV || new Array(6);
  36753. var faceColors = options.faceColors;
  36754. var colors = [];
  36755. // default face colors and UV if undefined
  36756. for (var f = 0; f < 6; f++) {
  36757. if (faceUV[f] === undefined) {
  36758. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36759. }
  36760. if (faceColors && faceColors[f] === undefined) {
  36761. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36762. }
  36763. }
  36764. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36765. // Create each face in turn.
  36766. for (var index = 0; index < normalsSource.length; index++) {
  36767. var normal = normalsSource[index];
  36768. // Get two vectors perpendicular to the face normal and to each other.
  36769. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36770. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36771. // Six indices (two triangles) per face.
  36772. var verticesLength = positions.length / 3;
  36773. indices.push(verticesLength);
  36774. indices.push(verticesLength + 1);
  36775. indices.push(verticesLength + 2);
  36776. indices.push(verticesLength);
  36777. indices.push(verticesLength + 2);
  36778. indices.push(verticesLength + 3);
  36779. // Four vertices per face.
  36780. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36781. positions.push(vertex.x, vertex.y, vertex.z);
  36782. normals.push(normal.x, normal.y, normal.z);
  36783. uvs.push(faceUV[index].z, faceUV[index].w);
  36784. if (faceColors) {
  36785. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36786. }
  36787. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36788. positions.push(vertex.x, vertex.y, vertex.z);
  36789. normals.push(normal.x, normal.y, normal.z);
  36790. uvs.push(faceUV[index].x, faceUV[index].w);
  36791. if (faceColors) {
  36792. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36793. }
  36794. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36795. positions.push(vertex.x, vertex.y, vertex.z);
  36796. normals.push(normal.x, normal.y, normal.z);
  36797. uvs.push(faceUV[index].x, faceUV[index].y);
  36798. if (faceColors) {
  36799. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36800. }
  36801. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36802. positions.push(vertex.x, vertex.y, vertex.z);
  36803. normals.push(normal.x, normal.y, normal.z);
  36804. uvs.push(faceUV[index].z, faceUV[index].y);
  36805. if (faceColors) {
  36806. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36807. }
  36808. }
  36809. // sides
  36810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36811. // Result
  36812. var vertexData = new VertexData();
  36813. vertexData.indices = indices;
  36814. vertexData.positions = positions;
  36815. vertexData.normals = normals;
  36816. vertexData.uvs = uvs;
  36817. if (faceColors) {
  36818. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36819. vertexData.colors = totalColors;
  36820. }
  36821. return vertexData;
  36822. };
  36823. /**
  36824. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36825. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36826. * * segments sets the number of horizontal strips optional, default 32
  36827. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36828. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36829. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36830. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36831. * * 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
  36832. * * 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
  36833. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36834. * * 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)
  36835. * * 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)
  36836. * @returns the VertexData of the ellipsoid
  36837. */
  36838. VertexData.CreateSphere = function (options) {
  36839. var segments = options.segments || 32;
  36840. var diameterX = options.diameterX || options.diameter || 1;
  36841. var diameterY = options.diameterY || options.diameter || 1;
  36842. var diameterZ = options.diameterZ || options.diameter || 1;
  36843. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36844. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36846. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36847. var totalZRotationSteps = 2 + segments;
  36848. var totalYRotationSteps = 2 * totalZRotationSteps;
  36849. var indices = [];
  36850. var positions = [];
  36851. var normals = [];
  36852. var uvs = [];
  36853. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36854. var normalizedZ = zRotationStep / totalZRotationSteps;
  36855. var angleZ = normalizedZ * Math.PI * slice;
  36856. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36857. var normalizedY = yRotationStep / totalYRotationSteps;
  36858. var angleY = normalizedY * Math.PI * 2 * arc;
  36859. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36860. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36861. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36862. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36863. var vertex = complete.multiply(radius);
  36864. var normal = complete.divide(radius).normalize();
  36865. positions.push(vertex.x, vertex.y, vertex.z);
  36866. normals.push(normal.x, normal.y, normal.z);
  36867. uvs.push(normalizedY, normalizedZ);
  36868. }
  36869. if (zRotationStep > 0) {
  36870. var verticesCount = positions.length / 3;
  36871. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36872. indices.push((firstIndex));
  36873. indices.push((firstIndex + 1));
  36874. indices.push(firstIndex + totalYRotationSteps + 1);
  36875. indices.push((firstIndex + totalYRotationSteps + 1));
  36876. indices.push((firstIndex + 1));
  36877. indices.push((firstIndex + totalYRotationSteps + 2));
  36878. }
  36879. }
  36880. }
  36881. // Sides
  36882. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36883. // Result
  36884. var vertexData = new VertexData();
  36885. vertexData.indices = indices;
  36886. vertexData.positions = positions;
  36887. vertexData.normals = normals;
  36888. vertexData.uvs = uvs;
  36889. return vertexData;
  36890. };
  36891. /**
  36892. * Creates the VertexData for a cylinder, cone or prism
  36893. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36894. * * height sets the height (y direction) of the cylinder, optional, default 2
  36895. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36896. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36897. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36898. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36899. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36900. * * 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
  36901. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36902. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36903. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36904. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36905. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36906. * * 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)
  36907. * * 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)
  36908. * @returns the VertexData of the cylinder, cone or prism
  36909. */
  36910. VertexData.CreateCylinder = function (options) {
  36911. var height = options.height || 2;
  36912. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36913. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36914. var tessellation = options.tessellation || 24;
  36915. var subdivisions = options.subdivisions || 1;
  36916. var hasRings = options.hasRings ? true : false;
  36917. var enclose = options.enclose ? true : false;
  36918. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36920. var faceUV = options.faceUV || new Array(3);
  36921. var faceColors = options.faceColors;
  36922. // default face colors and UV if undefined
  36923. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36924. var ringNb = (hasRings) ? subdivisions : 1;
  36925. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36926. var f;
  36927. for (f = 0; f < surfaceNb; f++) {
  36928. if (faceColors && faceColors[f] === undefined) {
  36929. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36930. }
  36931. }
  36932. for (f = 0; f < surfaceNb; f++) {
  36933. if (faceUV && faceUV[f] === undefined) {
  36934. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36935. }
  36936. }
  36937. var indices = new Array();
  36938. var positions = new Array();
  36939. var normals = new Array();
  36940. var uvs = new Array();
  36941. var colors = new Array();
  36942. var angle_step = Math.PI * 2 * arc / tessellation;
  36943. var angle;
  36944. var h;
  36945. var radius;
  36946. var tan = (diameterBottom - diameterTop) / 2 / height;
  36947. var ringVertex = BABYLON.Vector3.Zero();
  36948. var ringNormal = BABYLON.Vector3.Zero();
  36949. var ringFirstVertex = BABYLON.Vector3.Zero();
  36950. var ringFirstNormal = BABYLON.Vector3.Zero();
  36951. var quadNormal = BABYLON.Vector3.Zero();
  36952. var Y = BABYLON.Axis.Y;
  36953. // positions, normals, uvs
  36954. var i;
  36955. var j;
  36956. var r;
  36957. var ringIdx = 1;
  36958. var s = 1; // surface index
  36959. var cs = 0;
  36960. var v = 0;
  36961. for (i = 0; i <= subdivisions; i++) {
  36962. h = i / subdivisions;
  36963. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36964. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36965. for (r = 0; r < ringIdx; r++) {
  36966. if (hasRings) {
  36967. s += r;
  36968. }
  36969. if (enclose) {
  36970. s += 2 * r;
  36971. }
  36972. for (j = 0; j <= tessellation; j++) {
  36973. angle = j * angle_step;
  36974. // position
  36975. ringVertex.x = Math.cos(-angle) * radius;
  36976. ringVertex.y = -height / 2 + h * height;
  36977. ringVertex.z = Math.sin(-angle) * radius;
  36978. // normal
  36979. if (diameterTop === 0 && i === subdivisions) {
  36980. // if no top cap, reuse former normals
  36981. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36982. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36983. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36984. }
  36985. else {
  36986. ringNormal.x = ringVertex.x;
  36987. ringNormal.z = ringVertex.z;
  36988. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36989. ringNormal.normalize();
  36990. }
  36991. // keep first ring vertex values for enclose
  36992. if (j === 0) {
  36993. ringFirstVertex.copyFrom(ringVertex);
  36994. ringFirstNormal.copyFrom(ringNormal);
  36995. }
  36996. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36997. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36998. if (hasRings) {
  36999. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37000. }
  37001. else {
  37002. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37003. }
  37004. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37005. if (faceColors) {
  37006. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37007. }
  37008. }
  37009. // if enclose, add four vertices and their dedicated normals
  37010. if (arc !== 1 && enclose) {
  37011. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37012. positions.push(0, ringVertex.y, 0);
  37013. positions.push(0, ringVertex.y, 0);
  37014. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37015. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37016. quadNormal.normalize();
  37017. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37018. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37019. quadNormal.normalize();
  37020. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37021. if (hasRings) {
  37022. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37023. }
  37024. else {
  37025. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37026. }
  37027. uvs.push(faceUV[s + 1].x, v);
  37028. uvs.push(faceUV[s + 1].z, v);
  37029. if (hasRings) {
  37030. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37031. }
  37032. else {
  37033. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37034. }
  37035. uvs.push(faceUV[s + 2].x, v);
  37036. uvs.push(faceUV[s + 2].z, v);
  37037. if (faceColors) {
  37038. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37039. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37040. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37041. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37042. }
  37043. }
  37044. if (cs !== s) {
  37045. cs = s;
  37046. }
  37047. }
  37048. }
  37049. // indices
  37050. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37051. var s;
  37052. i = 0;
  37053. for (s = 0; s < subdivisions; s++) {
  37054. var i0 = 0;
  37055. var i1 = 0;
  37056. var i2 = 0;
  37057. var i3 = 0;
  37058. for (j = 0; j < tessellation; j++) {
  37059. i0 = i * (e + 1) + j;
  37060. i1 = (i + 1) * (e + 1) + j;
  37061. i2 = i * (e + 1) + (j + 1);
  37062. i3 = (i + 1) * (e + 1) + (j + 1);
  37063. indices.push(i0, i1, i2);
  37064. indices.push(i3, i2, i1);
  37065. }
  37066. if (arc !== 1 && enclose) { // if enclose, add two quads
  37067. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37068. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37069. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37070. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37071. }
  37072. i = (hasRings) ? (i + 2) : (i + 1);
  37073. }
  37074. // Caps
  37075. var createCylinderCap = function (isTop) {
  37076. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37077. if (radius === 0) {
  37078. return;
  37079. }
  37080. // Cap positions, normals & uvs
  37081. var angle;
  37082. var circleVector;
  37083. var i;
  37084. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37085. var c = null;
  37086. if (faceColors) {
  37087. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37088. }
  37089. // cap center
  37090. var vbase = positions.length / 3;
  37091. var offset = isTop ? height / 2 : -height / 2;
  37092. var center = new BABYLON.Vector3(0, offset, 0);
  37093. positions.push(center.x, center.y, center.z);
  37094. normals.push(0, isTop ? 1 : -1, 0);
  37095. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37096. if (c) {
  37097. colors.push(c.r, c.g, c.b, c.a);
  37098. }
  37099. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37100. for (i = 0; i <= tessellation; i++) {
  37101. angle = Math.PI * 2 * i * arc / tessellation;
  37102. var cos = Math.cos(-angle);
  37103. var sin = Math.sin(-angle);
  37104. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37105. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37106. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37107. normals.push(0, isTop ? 1 : -1, 0);
  37108. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37109. if (c) {
  37110. colors.push(c.r, c.g, c.b, c.a);
  37111. }
  37112. }
  37113. // Cap indices
  37114. for (i = 0; i < tessellation; i++) {
  37115. if (!isTop) {
  37116. indices.push(vbase);
  37117. indices.push(vbase + (i + 1));
  37118. indices.push(vbase + (i + 2));
  37119. }
  37120. else {
  37121. indices.push(vbase);
  37122. indices.push(vbase + (i + 2));
  37123. indices.push(vbase + (i + 1));
  37124. }
  37125. }
  37126. };
  37127. // add caps to geometry
  37128. createCylinderCap(false);
  37129. createCylinderCap(true);
  37130. // Sides
  37131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37132. var vertexData = new VertexData();
  37133. vertexData.indices = indices;
  37134. vertexData.positions = positions;
  37135. vertexData.normals = normals;
  37136. vertexData.uvs = uvs;
  37137. if (faceColors) {
  37138. vertexData.colors = colors;
  37139. }
  37140. return vertexData;
  37141. };
  37142. /**
  37143. * Creates the VertexData for a torus
  37144. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37145. * * diameter the diameter of the torus, optional default 1
  37146. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37147. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37148. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37149. * * 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)
  37150. * * 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)
  37151. * @returns the VertexData of the torus
  37152. */
  37153. VertexData.CreateTorus = function (options) {
  37154. var indices = [];
  37155. var positions = [];
  37156. var normals = [];
  37157. var uvs = [];
  37158. var diameter = options.diameter || 1;
  37159. var thickness = options.thickness || 0.5;
  37160. var tessellation = options.tessellation || 16;
  37161. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37162. var stride = tessellation + 1;
  37163. for (var i = 0; i <= tessellation; i++) {
  37164. var u = i / tessellation;
  37165. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37166. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37167. for (var j = 0; j <= tessellation; j++) {
  37168. var v = 1 - j / tessellation;
  37169. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37170. var dx = Math.cos(innerAngle);
  37171. var dy = Math.sin(innerAngle);
  37172. // Create a vertex.
  37173. var normal = new BABYLON.Vector3(dx, dy, 0);
  37174. var position = normal.scale(thickness / 2);
  37175. var textureCoordinate = new BABYLON.Vector2(u, v);
  37176. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37177. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37178. positions.push(position.x, position.y, position.z);
  37179. normals.push(normal.x, normal.y, normal.z);
  37180. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37181. // And create indices for two triangles.
  37182. var nextI = (i + 1) % stride;
  37183. var nextJ = (j + 1) % stride;
  37184. indices.push(i * stride + j);
  37185. indices.push(i * stride + nextJ);
  37186. indices.push(nextI * stride + j);
  37187. indices.push(i * stride + nextJ);
  37188. indices.push(nextI * stride + nextJ);
  37189. indices.push(nextI * stride + j);
  37190. }
  37191. }
  37192. // Sides
  37193. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37194. // Result
  37195. var vertexData = new VertexData();
  37196. vertexData.indices = indices;
  37197. vertexData.positions = positions;
  37198. vertexData.normals = normals;
  37199. vertexData.uvs = uvs;
  37200. return vertexData;
  37201. };
  37202. /**
  37203. * Creates the VertexData of the LineSystem
  37204. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37205. * - lines an array of lines, each line being an array of successive Vector3
  37206. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37207. * @returns the VertexData of the LineSystem
  37208. */
  37209. VertexData.CreateLineSystem = function (options) {
  37210. var indices = [];
  37211. var positions = [];
  37212. var lines = options.lines;
  37213. var colors = options.colors;
  37214. var vertexColors = [];
  37215. var idx = 0;
  37216. for (var l = 0; l < lines.length; l++) {
  37217. var points = lines[l];
  37218. for (var index = 0; index < points.length; index++) {
  37219. positions.push(points[index].x, points[index].y, points[index].z);
  37220. if (colors) {
  37221. var color = colors[l];
  37222. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37223. }
  37224. if (index > 0) {
  37225. indices.push(idx - 1);
  37226. indices.push(idx);
  37227. }
  37228. idx++;
  37229. }
  37230. }
  37231. var vertexData = new VertexData();
  37232. vertexData.indices = indices;
  37233. vertexData.positions = positions;
  37234. if (colors) {
  37235. vertexData.colors = vertexColors;
  37236. }
  37237. return vertexData;
  37238. };
  37239. /**
  37240. * Create the VertexData for a DashedLines
  37241. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37242. * - points an array successive Vector3
  37243. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37244. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37245. * - dashNb the intended total number of dashes, optional, default 200
  37246. * @returns the VertexData for the DashedLines
  37247. */
  37248. VertexData.CreateDashedLines = function (options) {
  37249. var dashSize = options.dashSize || 3;
  37250. var gapSize = options.gapSize || 1;
  37251. var dashNb = options.dashNb || 200;
  37252. var points = options.points;
  37253. var positions = new Array();
  37254. var indices = new Array();
  37255. var curvect = BABYLON.Vector3.Zero();
  37256. var lg = 0;
  37257. var nb = 0;
  37258. var shft = 0;
  37259. var dashshft = 0;
  37260. var curshft = 0;
  37261. var idx = 0;
  37262. var i = 0;
  37263. for (i = 0; i < points.length - 1; i++) {
  37264. points[i + 1].subtractToRef(points[i], curvect);
  37265. lg += curvect.length();
  37266. }
  37267. shft = lg / dashNb;
  37268. dashshft = dashSize * shft / (dashSize + gapSize);
  37269. for (i = 0; i < points.length - 1; i++) {
  37270. points[i + 1].subtractToRef(points[i], curvect);
  37271. nb = Math.floor(curvect.length() / shft);
  37272. curvect.normalize();
  37273. for (var j = 0; j < nb; j++) {
  37274. curshft = shft * j;
  37275. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37276. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37277. indices.push(idx, idx + 1);
  37278. idx += 2;
  37279. }
  37280. }
  37281. // Result
  37282. var vertexData = new VertexData();
  37283. vertexData.positions = positions;
  37284. vertexData.indices = indices;
  37285. return vertexData;
  37286. };
  37287. /**
  37288. * Creates the VertexData for a Ground
  37289. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37290. * - width the width (x direction) of the ground, optional, default 1
  37291. * - height the height (z direction) of the ground, optional, default 1
  37292. * - subdivisions the number of subdivisions per side, optional, default 1
  37293. * @returns the VertexData of the Ground
  37294. */
  37295. VertexData.CreateGround = function (options) {
  37296. var indices = [];
  37297. var positions = [];
  37298. var normals = [];
  37299. var uvs = [];
  37300. var row, col;
  37301. var width = options.width || 1;
  37302. var height = options.height || 1;
  37303. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37304. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37305. for (row = 0; row <= subdivisionsY; row++) {
  37306. for (col = 0; col <= subdivisionsX; col++) {
  37307. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37308. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37309. positions.push(position.x, position.y, position.z);
  37310. normals.push(normal.x, normal.y, normal.z);
  37311. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37312. }
  37313. }
  37314. for (row = 0; row < subdivisionsY; row++) {
  37315. for (col = 0; col < subdivisionsX; col++) {
  37316. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37317. indices.push(col + 1 + row * (subdivisionsX + 1));
  37318. indices.push(col + row * (subdivisionsX + 1));
  37319. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37320. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37321. indices.push(col + row * (subdivisionsX + 1));
  37322. }
  37323. }
  37324. // Result
  37325. var vertexData = new VertexData();
  37326. vertexData.indices = indices;
  37327. vertexData.positions = positions;
  37328. vertexData.normals = normals;
  37329. vertexData.uvs = uvs;
  37330. return vertexData;
  37331. };
  37332. /**
  37333. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37334. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37335. * * xmin the ground minimum X coordinate, optional, default -1
  37336. * * zmin the ground minimum Z coordinate, optional, default -1
  37337. * * xmax the ground maximum X coordinate, optional, default 1
  37338. * * zmax the ground maximum Z coordinate, optional, default 1
  37339. * * 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}
  37340. * * 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}
  37341. * @returns the VertexData of the TiledGround
  37342. */
  37343. VertexData.CreateTiledGround = function (options) {
  37344. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37345. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37346. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37347. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37348. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37349. var precision = options.precision || { w: 1, h: 1 };
  37350. var indices = new Array();
  37351. var positions = new Array();
  37352. var normals = new Array();
  37353. var uvs = new Array();
  37354. var row, col, tileRow, tileCol;
  37355. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37356. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37357. precision.w = (precision.w < 1) ? 1 : precision.w;
  37358. precision.h = (precision.h < 1) ? 1 : precision.h;
  37359. var tileSize = {
  37360. 'w': (xmax - xmin) / subdivisions.w,
  37361. 'h': (zmax - zmin) / subdivisions.h
  37362. };
  37363. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37364. // Indices
  37365. var base = positions.length / 3;
  37366. var rowLength = precision.w + 1;
  37367. for (row = 0; row < precision.h; row++) {
  37368. for (col = 0; col < precision.w; col++) {
  37369. var square = [
  37370. base + col + row * rowLength,
  37371. base + (col + 1) + row * rowLength,
  37372. base + (col + 1) + (row + 1) * rowLength,
  37373. base + col + (row + 1) * rowLength
  37374. ];
  37375. indices.push(square[1]);
  37376. indices.push(square[2]);
  37377. indices.push(square[3]);
  37378. indices.push(square[0]);
  37379. indices.push(square[1]);
  37380. indices.push(square[3]);
  37381. }
  37382. }
  37383. // Position, normals and uvs
  37384. var position = BABYLON.Vector3.Zero();
  37385. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37386. for (row = 0; row <= precision.h; row++) {
  37387. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37388. for (col = 0; col <= precision.w; col++) {
  37389. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37390. position.y = 0;
  37391. positions.push(position.x, position.y, position.z);
  37392. normals.push(normal.x, normal.y, normal.z);
  37393. uvs.push(col / precision.w, row / precision.h);
  37394. }
  37395. }
  37396. }
  37397. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37398. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37399. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37400. }
  37401. }
  37402. // Result
  37403. var vertexData = new VertexData();
  37404. vertexData.indices = indices;
  37405. vertexData.positions = positions;
  37406. vertexData.normals = normals;
  37407. vertexData.uvs = uvs;
  37408. return vertexData;
  37409. };
  37410. /**
  37411. * Creates the VertexData of the Ground designed from a heightmap
  37412. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37413. * * width the width (x direction) of the ground
  37414. * * height the height (z direction) of the ground
  37415. * * subdivisions the number of subdivisions per side
  37416. * * minHeight the minimum altitude on the ground, optional, default 0
  37417. * * maxHeight the maximum altitude on the ground, optional default 1
  37418. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37419. * * buffer the array holding the image color data
  37420. * * bufferWidth the width of image
  37421. * * bufferHeight the height of image
  37422. * @returns the VertexData of the Ground designed from a heightmap
  37423. */
  37424. VertexData.CreateGroundFromHeightMap = function (options) {
  37425. var indices = [];
  37426. var positions = [];
  37427. var normals = [];
  37428. var uvs = [];
  37429. var row, col;
  37430. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37431. // Vertices
  37432. for (row = 0; row <= options.subdivisions; row++) {
  37433. for (col = 0; col <= options.subdivisions; col++) {
  37434. 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));
  37435. // Compute height
  37436. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37437. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37438. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37439. var r = options.buffer[pos] / 255.0;
  37440. var g = options.buffer[pos + 1] / 255.0;
  37441. var b = options.buffer[pos + 2] / 255.0;
  37442. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37443. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37444. // Add vertex
  37445. positions.push(position.x, position.y, position.z);
  37446. normals.push(0, 0, 0);
  37447. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37448. }
  37449. }
  37450. // Indices
  37451. for (row = 0; row < options.subdivisions; row++) {
  37452. for (col = 0; col < options.subdivisions; col++) {
  37453. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37454. indices.push(col + 1 + row * (options.subdivisions + 1));
  37455. indices.push(col + row * (options.subdivisions + 1));
  37456. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37457. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37458. indices.push(col + row * (options.subdivisions + 1));
  37459. }
  37460. }
  37461. // Normals
  37462. VertexData.ComputeNormals(positions, indices, normals);
  37463. // Result
  37464. var vertexData = new VertexData();
  37465. vertexData.indices = indices;
  37466. vertexData.positions = positions;
  37467. vertexData.normals = normals;
  37468. vertexData.uvs = uvs;
  37469. return vertexData;
  37470. };
  37471. /**
  37472. * Creates the VertexData for a Plane
  37473. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37474. * * size sets the width and height of the plane to the value of size, optional default 1
  37475. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37476. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37477. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37478. * * 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)
  37479. * * 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)
  37480. * @returns the VertexData of the box
  37481. */
  37482. VertexData.CreatePlane = function (options) {
  37483. var indices = [];
  37484. var positions = [];
  37485. var normals = [];
  37486. var uvs = [];
  37487. var width = options.width || options.size || 1;
  37488. var height = options.height || options.size || 1;
  37489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37490. // Vertices
  37491. var halfWidth = width / 2.0;
  37492. var halfHeight = height / 2.0;
  37493. positions.push(-halfWidth, -halfHeight, 0);
  37494. normals.push(0, 0, -1.0);
  37495. uvs.push(0.0, 0.0);
  37496. positions.push(halfWidth, -halfHeight, 0);
  37497. normals.push(0, 0, -1.0);
  37498. uvs.push(1.0, 0.0);
  37499. positions.push(halfWidth, halfHeight, 0);
  37500. normals.push(0, 0, -1.0);
  37501. uvs.push(1.0, 1.0);
  37502. positions.push(-halfWidth, halfHeight, 0);
  37503. normals.push(0, 0, -1.0);
  37504. uvs.push(0.0, 1.0);
  37505. // Indices
  37506. indices.push(0);
  37507. indices.push(1);
  37508. indices.push(2);
  37509. indices.push(0);
  37510. indices.push(2);
  37511. indices.push(3);
  37512. // Sides
  37513. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37514. // Result
  37515. var vertexData = new VertexData();
  37516. vertexData.indices = indices;
  37517. vertexData.positions = positions;
  37518. vertexData.normals = normals;
  37519. vertexData.uvs = uvs;
  37520. return vertexData;
  37521. };
  37522. /**
  37523. * Creates the VertexData of the Disc or regular Polygon
  37524. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37525. * * radius the radius of the disc, optional default 0.5
  37526. * * tessellation the number of polygon sides, optional, default 64
  37527. * * 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
  37528. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37529. * * 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)
  37530. * * 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)
  37531. * @returns the VertexData of the box
  37532. */
  37533. VertexData.CreateDisc = function (options) {
  37534. var positions = new Array();
  37535. var indices = new Array();
  37536. var normals = new Array();
  37537. var uvs = new Array();
  37538. var radius = options.radius || 0.5;
  37539. var tessellation = options.tessellation || 64;
  37540. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37542. // positions and uvs
  37543. positions.push(0, 0, 0); // disc center first
  37544. uvs.push(0.5, 0.5);
  37545. var theta = Math.PI * 2 * arc;
  37546. var step = theta / tessellation;
  37547. for (var a = 0; a < theta; a += step) {
  37548. var x = Math.cos(a);
  37549. var y = Math.sin(a);
  37550. var u = (x + 1) / 2;
  37551. var v = (1 - y) / 2;
  37552. positions.push(radius * x, radius * y, 0);
  37553. uvs.push(u, v);
  37554. }
  37555. if (arc === 1) {
  37556. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37557. uvs.push(uvs[2], uvs[3]);
  37558. }
  37559. //indices
  37560. var vertexNb = positions.length / 3;
  37561. for (var i = 1; i < vertexNb - 1; i++) {
  37562. indices.push(i + 1, 0, i);
  37563. }
  37564. // result
  37565. VertexData.ComputeNormals(positions, indices, normals);
  37566. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37567. var vertexData = new VertexData();
  37568. vertexData.indices = indices;
  37569. vertexData.positions = positions;
  37570. vertexData.normals = normals;
  37571. vertexData.uvs = uvs;
  37572. return vertexData;
  37573. };
  37574. /**
  37575. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37576. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37577. * @param polygon a mesh built from polygonTriangulation.build()
  37578. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37579. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37580. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37581. * @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)
  37582. * @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)
  37583. * @returns the VertexData of the Polygon
  37584. */
  37585. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37586. var faceUV = fUV || new Array(3);
  37587. var faceColors = fColors;
  37588. var colors = [];
  37589. // default face colors and UV if undefined
  37590. for (var f = 0; f < 3; f++) {
  37591. if (faceUV[f] === undefined) {
  37592. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37593. }
  37594. if (faceColors && faceColors[f] === undefined) {
  37595. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37596. }
  37597. }
  37598. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37599. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37600. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37601. var indices = polygon.getIndices();
  37602. // set face colours and textures
  37603. var idx = 0;
  37604. var face = 0;
  37605. for (var index = 0; index < normals.length; index += 3) {
  37606. //Edge Face no. 1
  37607. if (Math.abs(normals[index + 1]) < 0.001) {
  37608. face = 1;
  37609. }
  37610. //Top Face no. 0
  37611. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37612. face = 0;
  37613. }
  37614. //Bottom Face no. 2
  37615. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37616. face = 2;
  37617. }
  37618. idx = index / 3;
  37619. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37620. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37621. if (faceColors) {
  37622. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37623. }
  37624. }
  37625. // sides
  37626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37627. // Result
  37628. var vertexData = new VertexData();
  37629. vertexData.indices = indices;
  37630. vertexData.positions = positions;
  37631. vertexData.normals = normals;
  37632. vertexData.uvs = uvs;
  37633. if (faceColors) {
  37634. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37635. vertexData.colors = totalColors;
  37636. }
  37637. return vertexData;
  37638. };
  37639. /**
  37640. * Creates the VertexData of the IcoSphere
  37641. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37642. * * radius the radius of the IcoSphere, optional default 1
  37643. * * radiusX allows stretching in the x direction, optional, default radius
  37644. * * radiusY allows stretching in the y direction, optional, default radius
  37645. * * radiusZ allows stretching in the z direction, optional, default radius
  37646. * * flat when true creates a flat shaded mesh, optional, default true
  37647. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37648. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37649. * * 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)
  37650. * * 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)
  37651. * @returns the VertexData of the IcoSphere
  37652. */
  37653. VertexData.CreateIcoSphere = function (options) {
  37654. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37655. var radius = options.radius || 1;
  37656. var flat = (options.flat === undefined) ? true : options.flat;
  37657. var subdivisions = options.subdivisions || 4;
  37658. var radiusX = options.radiusX || radius;
  37659. var radiusY = options.radiusY || radius;
  37660. var radiusZ = options.radiusZ || radius;
  37661. var t = (1 + Math.sqrt(5)) / 2;
  37662. // 12 vertex x,y,z
  37663. var ico_vertices = [
  37664. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37665. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37666. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37667. ];
  37668. // index of 3 vertex makes a face of icopshere
  37669. var ico_indices = [
  37670. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37671. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37672. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37673. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37674. ];
  37675. // vertex for uv have aliased position, not for UV
  37676. var vertices_unalias_id = [
  37677. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37678. // vertex alias
  37679. 0,
  37680. 2,
  37681. 3,
  37682. 3,
  37683. 3,
  37684. 4,
  37685. 7,
  37686. 8,
  37687. 9,
  37688. 9,
  37689. 10,
  37690. 11 // 23: B + 12
  37691. ];
  37692. // uv as integer step (not pixels !)
  37693. var ico_vertexuv = [
  37694. 5, 1, 3, 1, 6, 4, 0, 0,
  37695. 5, 3, 4, 2, 2, 2, 4, 0,
  37696. 2, 0, 1, 1, 6, 0, 6, 2,
  37697. // vertex alias (for same vertex on different faces)
  37698. 0, 4,
  37699. 3, 3,
  37700. 4, 4,
  37701. 3, 1,
  37702. 4, 2,
  37703. 4, 4,
  37704. 0, 2,
  37705. 1, 1,
  37706. 2, 2,
  37707. 3, 3,
  37708. 1, 3,
  37709. 2, 4 // 23: B + 12
  37710. ];
  37711. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37712. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37713. // First island of uv mapping
  37714. // v = 4h 3+ 2
  37715. // v = 3h 9+ 4
  37716. // v = 2h 9+ 5 B
  37717. // v = 1h 9 1 0
  37718. // v = 0h 3 8 7 A
  37719. // u = 0 1 2 3 4 5 6 *a
  37720. // Second island of uv mapping
  37721. // v = 4h 0+ B+ 4+
  37722. // v = 3h A+ 2+
  37723. // v = 2h 7+ 6 3+
  37724. // v = 1h 8+ 3+
  37725. // v = 0h
  37726. // u = 0 1 2 3 4 5 6 *a
  37727. // Face layout on texture UV mapping
  37728. // ============
  37729. // \ 4 /\ 16 / ======
  37730. // \ / \ / /\ 11 /
  37731. // \/ 7 \/ / \ /
  37732. // ======= / 10 \/
  37733. // /\ 17 /\ =======
  37734. // / \ / \ \ 15 /\
  37735. // / 8 \/ 12 \ \ / \
  37736. // ============ \/ 6 \
  37737. // \ 18 /\ ============
  37738. // \ / \ \ 5 /\ 0 /
  37739. // \/ 13 \ \ / \ /
  37740. // ======= \/ 1 \/
  37741. // =============
  37742. // /\ 19 /\ 2 /\
  37743. // / \ / \ / \
  37744. // / 14 \/ 9 \/ 3 \
  37745. // ===================
  37746. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37747. var ustep = 138 / 1024;
  37748. var vstep = 239 / 1024;
  37749. var uoffset = 60 / 1024;
  37750. var voffset = 26 / 1024;
  37751. // Second island should have margin, not to touch the first island
  37752. // avoid any borderline artefact in pixel rounding
  37753. var island_u_offset = -40 / 1024;
  37754. var island_v_offset = +20 / 1024;
  37755. // face is either island 0 or 1 :
  37756. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37757. var island = [
  37758. 0, 0, 0, 0, 1,
  37759. 0, 0, 1, 1, 0,
  37760. 0, 0, 1, 1, 0,
  37761. 0, 1, 1, 1, 0 // 15 - 19
  37762. ];
  37763. var indices = new Array();
  37764. var positions = new Array();
  37765. var normals = new Array();
  37766. var uvs = new Array();
  37767. var current_indice = 0;
  37768. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37769. var face_vertex_pos = new Array(3);
  37770. var face_vertex_uv = new Array(3);
  37771. var v012;
  37772. for (v012 = 0; v012 < 3; v012++) {
  37773. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37774. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37775. }
  37776. // create all with normals
  37777. for (var face = 0; face < 20; face++) {
  37778. // 3 vertex per face
  37779. for (v012 = 0; v012 < 3; v012++) {
  37780. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37781. var v_id = ico_indices[3 * face + v012];
  37782. // vertex have 3D position (x,y,z)
  37783. 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]);
  37784. // Normalize to get normal, then scale to radius
  37785. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37786. // uv Coordinates from vertex ID
  37787. 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);
  37788. }
  37789. // Subdivide the face (interpolate pos, norm, uv)
  37790. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37791. // - norm is linear interpolation of vertex corner normal
  37792. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37793. // - uv is linear interpolation
  37794. //
  37795. // Topology is as below for sub-divide by 2
  37796. // vertex shown as v0,v1,v2
  37797. // interp index is i1 to progress in range [v0,v1[
  37798. // interp index is i2 to progress in range [v0,v2[
  37799. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37800. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37801. //
  37802. //
  37803. // i2 v2
  37804. // ^ ^
  37805. // / / \
  37806. // / / \
  37807. // / / \
  37808. // / / (0,1) \
  37809. // / #---------\
  37810. // / / \ (0,0)'/ \
  37811. // / / \ / \
  37812. // / / \ / \
  37813. // / / (0,0) \ / (1,0) \
  37814. // / #---------#---------\
  37815. // v0 v1
  37816. //
  37817. // --------------------> i1
  37818. //
  37819. // interp of (i1,i2):
  37820. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37821. // along i1 : lerp(x0,x1, i1/(S-i2))
  37822. //
  37823. // centroid of triangle is needed to get help normal computation
  37824. // (c1,c2) are used for centroid location
  37825. var interp_vertex = function (i1, i2, c1, c2) {
  37826. // vertex is interpolated from
  37827. // - face_vertex_pos[0..2]
  37828. // - face_vertex_uv[0..2]
  37829. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37830. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37831. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37832. pos_interp.normalize();
  37833. var vertex_normal;
  37834. if (flat) {
  37835. // in flat mode, recalculate normal as face centroid normal
  37836. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37837. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37838. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37839. }
  37840. else {
  37841. // in smooth mode, recalculate normal from each single vertex position
  37842. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37843. }
  37844. // Vertex normal need correction due to X,Y,Z radius scaling
  37845. vertex_normal.x /= radiusX;
  37846. vertex_normal.y /= radiusY;
  37847. vertex_normal.z /= radiusZ;
  37848. vertex_normal.normalize();
  37849. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37850. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37851. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37852. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37853. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37854. uvs.push(uv_interp.x, uv_interp.y);
  37855. // push each vertex has member of a face
  37856. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37857. indices.push(current_indice);
  37858. current_indice++;
  37859. };
  37860. for (var i2 = 0; i2 < subdivisions; i2++) {
  37861. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37862. // face : (i1,i2) for /\ :
  37863. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37864. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37865. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37866. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37867. if (i1 + i2 + 1 < subdivisions) {
  37868. // face : (i1,i2)' for \/ :
  37869. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37870. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37871. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37872. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37873. }
  37874. }
  37875. }
  37876. }
  37877. // Sides
  37878. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37879. // Result
  37880. var vertexData = new VertexData();
  37881. vertexData.indices = indices;
  37882. vertexData.positions = positions;
  37883. vertexData.normals = normals;
  37884. vertexData.uvs = uvs;
  37885. return vertexData;
  37886. };
  37887. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37888. /**
  37889. * Creates the VertexData for a Polyhedron
  37890. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37891. * * type provided types are:
  37892. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37893. * * 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)
  37894. * * size the size of the IcoSphere, optional default 1
  37895. * * sizeX allows stretching in the x direction, optional, default size
  37896. * * sizeY allows stretching in the y direction, optional, default size
  37897. * * sizeZ allows stretching in the z direction, optional, default size
  37898. * * 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
  37899. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37900. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37901. * * flat when true creates a flat shaded mesh, optional, default true
  37902. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37903. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37904. * * 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)
  37905. * * 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)
  37906. * @returns the VertexData of the Polyhedron
  37907. */
  37908. VertexData.CreatePolyhedron = function (options) {
  37909. // provided polyhedron types :
  37910. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37911. // 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)
  37912. var polyhedra = [];
  37913. 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]] };
  37914. 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]] };
  37915. polyhedra[2] = {
  37916. 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]],
  37917. 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]]
  37918. };
  37919. polyhedra[3] = {
  37920. 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]],
  37921. 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]]
  37922. };
  37923. polyhedra[4] = {
  37924. 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]],
  37925. 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]]
  37926. };
  37927. 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]] };
  37928. 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]] };
  37929. 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]] };
  37930. 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]] };
  37931. 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]] };
  37932. 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]] };
  37933. 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]] };
  37934. 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]] };
  37935. 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]] };
  37936. polyhedra[14] = {
  37937. 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]],
  37938. 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]]
  37939. };
  37940. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37941. var size = options.size;
  37942. var sizeX = options.sizeX || size || 1;
  37943. var sizeY = options.sizeY || size || 1;
  37944. var sizeZ = options.sizeZ || size || 1;
  37945. var data = options.custom || polyhedra[type];
  37946. var nbfaces = data.face.length;
  37947. var faceUV = options.faceUV || new Array(nbfaces);
  37948. var faceColors = options.faceColors;
  37949. var flat = (options.flat === undefined) ? true : options.flat;
  37950. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37951. var positions = new Array();
  37952. var indices = new Array();
  37953. var normals = new Array();
  37954. var uvs = new Array();
  37955. var colors = new Array();
  37956. var index = 0;
  37957. var faceIdx = 0; // face cursor in the array "indexes"
  37958. var indexes = new Array();
  37959. var i = 0;
  37960. var f = 0;
  37961. var u, v, ang, x, y, tmp;
  37962. // default face colors and UV if undefined
  37963. if (flat) {
  37964. for (f = 0; f < nbfaces; f++) {
  37965. if (faceColors && faceColors[f] === undefined) {
  37966. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37967. }
  37968. if (faceUV && faceUV[f] === undefined) {
  37969. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37970. }
  37971. }
  37972. }
  37973. if (!flat) {
  37974. for (i = 0; i < data.vertex.length; i++) {
  37975. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37976. uvs.push(0, 0);
  37977. }
  37978. for (f = 0; f < nbfaces; f++) {
  37979. for (i = 0; i < data.face[f].length - 2; i++) {
  37980. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37981. }
  37982. }
  37983. }
  37984. else {
  37985. for (f = 0; f < nbfaces; f++) {
  37986. var fl = data.face[f].length; // number of vertices of the current face
  37987. ang = 2 * Math.PI / fl;
  37988. x = 0.5 * Math.tan(ang / 2);
  37989. y = 0.5;
  37990. // positions, uvs, colors
  37991. for (i = 0; i < fl; i++) {
  37992. // positions
  37993. 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);
  37994. indexes.push(index);
  37995. index++;
  37996. // uvs
  37997. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37998. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37999. uvs.push(u, v);
  38000. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38001. y = x * Math.sin(ang) + y * Math.cos(ang);
  38002. x = tmp;
  38003. // colors
  38004. if (faceColors) {
  38005. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38006. }
  38007. }
  38008. // indices from indexes
  38009. for (i = 0; i < fl - 2; i++) {
  38010. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38011. }
  38012. faceIdx += fl;
  38013. }
  38014. }
  38015. VertexData.ComputeNormals(positions, indices, normals);
  38016. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38017. var vertexData = new VertexData();
  38018. vertexData.positions = positions;
  38019. vertexData.indices = indices;
  38020. vertexData.normals = normals;
  38021. vertexData.uvs = uvs;
  38022. if (faceColors && flat) {
  38023. vertexData.colors = colors;
  38024. }
  38025. return vertexData;
  38026. };
  38027. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38028. /**
  38029. * Creates the VertexData for a TorusKnot
  38030. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38031. * * radius the radius of the torus knot, optional, default 2
  38032. * * tube the thickness of the tube, optional, default 0.5
  38033. * * radialSegments the number of sides on each tube segments, optional, default 32
  38034. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38035. * * p the number of windings around the z axis, optional, default 2
  38036. * * q the number of windings around the x axis, optional, default 3
  38037. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38038. * * 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)
  38039. * * 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)
  38040. * @returns the VertexData of the Torus Knot
  38041. */
  38042. VertexData.CreateTorusKnot = function (options) {
  38043. var indices = new Array();
  38044. var positions = new Array();
  38045. var normals = new Array();
  38046. var uvs = new Array();
  38047. var radius = options.radius || 2;
  38048. var tube = options.tube || 0.5;
  38049. var radialSegments = options.radialSegments || 32;
  38050. var tubularSegments = options.tubularSegments || 32;
  38051. var p = options.p || 2;
  38052. var q = options.q || 3;
  38053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38054. // Helper
  38055. var getPos = function (angle) {
  38056. var cu = Math.cos(angle);
  38057. var su = Math.sin(angle);
  38058. var quOverP = q / p * angle;
  38059. var cs = Math.cos(quOverP);
  38060. var tx = radius * (2 + cs) * 0.5 * cu;
  38061. var ty = radius * (2 + cs) * su * 0.5;
  38062. var tz = radius * Math.sin(quOverP) * 0.5;
  38063. return new BABYLON.Vector3(tx, ty, tz);
  38064. };
  38065. // Vertices
  38066. var i;
  38067. var j;
  38068. for (i = 0; i <= radialSegments; i++) {
  38069. var modI = i % radialSegments;
  38070. var u = modI / radialSegments * 2 * p * Math.PI;
  38071. var p1 = getPos(u);
  38072. var p2 = getPos(u + 0.01);
  38073. var tang = p2.subtract(p1);
  38074. var n = p2.add(p1);
  38075. var bitan = BABYLON.Vector3.Cross(tang, n);
  38076. n = BABYLON.Vector3.Cross(bitan, tang);
  38077. bitan.normalize();
  38078. n.normalize();
  38079. for (j = 0; j < tubularSegments; j++) {
  38080. var modJ = j % tubularSegments;
  38081. var v = modJ / tubularSegments * 2 * Math.PI;
  38082. var cx = -tube * Math.cos(v);
  38083. var cy = tube * Math.sin(v);
  38084. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38085. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38086. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38087. uvs.push(i / radialSegments);
  38088. uvs.push(j / tubularSegments);
  38089. }
  38090. }
  38091. for (i = 0; i < radialSegments; i++) {
  38092. for (j = 0; j < tubularSegments; j++) {
  38093. var jNext = (j + 1) % tubularSegments;
  38094. var a = i * tubularSegments + j;
  38095. var b = (i + 1) * tubularSegments + j;
  38096. var c = (i + 1) * tubularSegments + jNext;
  38097. var d = i * tubularSegments + jNext;
  38098. indices.push(d);
  38099. indices.push(b);
  38100. indices.push(a);
  38101. indices.push(d);
  38102. indices.push(c);
  38103. indices.push(b);
  38104. }
  38105. }
  38106. // Normals
  38107. VertexData.ComputeNormals(positions, indices, normals);
  38108. // Sides
  38109. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38110. // Result
  38111. var vertexData = new VertexData();
  38112. vertexData.indices = indices;
  38113. vertexData.positions = positions;
  38114. vertexData.normals = normals;
  38115. vertexData.uvs = uvs;
  38116. return vertexData;
  38117. };
  38118. // Tools
  38119. /**
  38120. * Compute normals for given positions and indices
  38121. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38122. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38123. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38124. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38125. * * facetNormals : optional array of facet normals (vector3)
  38126. * * facetPositions : optional array of facet positions (vector3)
  38127. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38128. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38129. * * bInfo : optional bounding info, required for facetPartitioning computation
  38130. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38131. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38132. * * useRightHandedSystem: optional boolean to for right handed system computation
  38133. * * depthSort : optional boolean to enable the facet depth sort computation
  38134. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38135. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38136. */
  38137. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38138. // temporary scalar variables
  38139. var index = 0; // facet index
  38140. var p1p2x = 0.0; // p1p2 vector x coordinate
  38141. var p1p2y = 0.0; // p1p2 vector y coordinate
  38142. var p1p2z = 0.0; // p1p2 vector z coordinate
  38143. var p3p2x = 0.0; // p3p2 vector x coordinate
  38144. var p3p2y = 0.0; // p3p2 vector y coordinate
  38145. var p3p2z = 0.0; // p3p2 vector z coordinate
  38146. var faceNormalx = 0.0; // facet normal x coordinate
  38147. var faceNormaly = 0.0; // facet normal y coordinate
  38148. var faceNormalz = 0.0; // facet normal z coordinate
  38149. var length = 0.0; // facet normal length before normalization
  38150. var v1x = 0; // vector1 x index in the positions array
  38151. var v1y = 0; // vector1 y index in the positions array
  38152. var v1z = 0; // vector1 z index in the positions array
  38153. var v2x = 0; // vector2 x index in the positions array
  38154. var v2y = 0; // vector2 y index in the positions array
  38155. var v2z = 0; // vector2 z index in the positions array
  38156. var v3x = 0; // vector3 x index in the positions array
  38157. var v3y = 0; // vector3 y index in the positions array
  38158. var v3z = 0; // vector3 z index in the positions array
  38159. var computeFacetNormals = false;
  38160. var computeFacetPositions = false;
  38161. var computeFacetPartitioning = false;
  38162. var computeDepthSort = false;
  38163. var faceNormalSign = 1;
  38164. var ratio = 0;
  38165. var distanceTo = null;
  38166. if (options) {
  38167. computeFacetNormals = (options.facetNormals) ? true : false;
  38168. computeFacetPositions = (options.facetPositions) ? true : false;
  38169. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38170. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38171. ratio = options.ratio || 0;
  38172. computeDepthSort = (options.depthSort) ? true : false;
  38173. distanceTo = (options.distanceTo);
  38174. if (computeDepthSort) {
  38175. if (distanceTo === undefined) {
  38176. distanceTo = BABYLON.Vector3.Zero();
  38177. }
  38178. var depthSortedFacets = options.depthSortedFacets;
  38179. }
  38180. }
  38181. // facetPartitioning reinit if needed
  38182. var xSubRatio = 0;
  38183. var ySubRatio = 0;
  38184. var zSubRatio = 0;
  38185. var subSq = 0;
  38186. if (computeFacetPartitioning && options && options.bbSize) {
  38187. var ox = 0; // X partitioning index for facet position
  38188. var oy = 0; // Y partinioning index for facet position
  38189. var oz = 0; // Z partinioning index for facet position
  38190. var b1x = 0; // X partitioning index for facet v1 vertex
  38191. var b1y = 0; // Y partitioning index for facet v1 vertex
  38192. var b1z = 0; // z partitioning index for facet v1 vertex
  38193. var b2x = 0; // X partitioning index for facet v2 vertex
  38194. var b2y = 0; // Y partitioning index for facet v2 vertex
  38195. var b2z = 0; // Z partitioning index for facet v2 vertex
  38196. var b3x = 0; // X partitioning index for facet v3 vertex
  38197. var b3y = 0; // Y partitioning index for facet v3 vertex
  38198. var b3z = 0; // Z partitioning index for facet v3 vertex
  38199. var block_idx_o = 0; // facet barycenter block index
  38200. var block_idx_v1 = 0; // v1 vertex block index
  38201. var block_idx_v2 = 0; // v2 vertex block index
  38202. var block_idx_v3 = 0; // v3 vertex block index
  38203. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38204. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38205. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38206. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38207. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38208. subSq = options.subDiv.max * options.subDiv.max;
  38209. options.facetPartitioning.length = 0;
  38210. }
  38211. // reset the normals
  38212. for (index = 0; index < positions.length; index++) {
  38213. normals[index] = 0.0;
  38214. }
  38215. // Loop : 1 indice triplet = 1 facet
  38216. var nbFaces = (indices.length / 3) | 0;
  38217. for (index = 0; index < nbFaces; index++) {
  38218. // get the indexes of the coordinates of each vertex of the facet
  38219. v1x = indices[index * 3] * 3;
  38220. v1y = v1x + 1;
  38221. v1z = v1x + 2;
  38222. v2x = indices[index * 3 + 1] * 3;
  38223. v2y = v2x + 1;
  38224. v2z = v2x + 2;
  38225. v3x = indices[index * 3 + 2] * 3;
  38226. v3y = v3x + 1;
  38227. v3z = v3x + 2;
  38228. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38229. p1p2y = positions[v1y] - positions[v2y];
  38230. p1p2z = positions[v1z] - positions[v2z];
  38231. p3p2x = positions[v3x] - positions[v2x];
  38232. p3p2y = positions[v3y] - positions[v2y];
  38233. p3p2z = positions[v3z] - positions[v2z];
  38234. // compute the face normal with the cross product
  38235. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38236. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38237. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38238. // normalize this normal and store it in the array facetData
  38239. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38240. length = (length === 0) ? 1.0 : length;
  38241. faceNormalx /= length;
  38242. faceNormaly /= length;
  38243. faceNormalz /= length;
  38244. if (computeFacetNormals && options) {
  38245. options.facetNormals[index].x = faceNormalx;
  38246. options.facetNormals[index].y = faceNormaly;
  38247. options.facetNormals[index].z = faceNormalz;
  38248. }
  38249. if (computeFacetPositions && options) {
  38250. // compute and the facet barycenter coordinates in the array facetPositions
  38251. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38252. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38253. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38254. }
  38255. if (computeFacetPartitioning && options) {
  38256. // store the facet indexes in arrays in the main facetPartitioning array :
  38257. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38258. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38259. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38260. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38261. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38262. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38263. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38264. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38265. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38266. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38267. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38268. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38269. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38270. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38271. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38272. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38273. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38274. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38275. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38276. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38277. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38278. // push each facet index in each block containing the vertex
  38279. options.facetPartitioning[block_idx_v1].push(index);
  38280. if (block_idx_v2 != block_idx_v1) {
  38281. options.facetPartitioning[block_idx_v2].push(index);
  38282. }
  38283. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38284. options.facetPartitioning[block_idx_v3].push(index);
  38285. }
  38286. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38287. options.facetPartitioning[block_idx_o].push(index);
  38288. }
  38289. }
  38290. if (computeDepthSort && options && options.facetPositions) {
  38291. var dsf = depthSortedFacets[index];
  38292. dsf.ind = index * 3;
  38293. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38294. }
  38295. // compute the normals anyway
  38296. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38297. normals[v1y] += faceNormaly;
  38298. normals[v1z] += faceNormalz;
  38299. normals[v2x] += faceNormalx;
  38300. normals[v2y] += faceNormaly;
  38301. normals[v2z] += faceNormalz;
  38302. normals[v3x] += faceNormalx;
  38303. normals[v3y] += faceNormaly;
  38304. normals[v3z] += faceNormalz;
  38305. }
  38306. // last normalization of each normal
  38307. for (index = 0; index < normals.length / 3; index++) {
  38308. faceNormalx = normals[index * 3];
  38309. faceNormaly = normals[index * 3 + 1];
  38310. faceNormalz = normals[index * 3 + 2];
  38311. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38312. length = (length === 0) ? 1.0 : length;
  38313. faceNormalx /= length;
  38314. faceNormaly /= length;
  38315. faceNormalz /= length;
  38316. normals[index * 3] = faceNormalx;
  38317. normals[index * 3 + 1] = faceNormaly;
  38318. normals[index * 3 + 2] = faceNormalz;
  38319. }
  38320. };
  38321. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38322. var li = indices.length;
  38323. var ln = normals.length;
  38324. var i;
  38325. var n;
  38326. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38327. switch (sideOrientation) {
  38328. case BABYLON.Mesh.FRONTSIDE:
  38329. // nothing changed
  38330. break;
  38331. case BABYLON.Mesh.BACKSIDE:
  38332. var tmp;
  38333. // indices
  38334. for (i = 0; i < li; i += 3) {
  38335. tmp = indices[i];
  38336. indices[i] = indices[i + 2];
  38337. indices[i + 2] = tmp;
  38338. }
  38339. // normals
  38340. for (n = 0; n < ln; n++) {
  38341. normals[n] = -normals[n];
  38342. }
  38343. break;
  38344. case BABYLON.Mesh.DOUBLESIDE:
  38345. // positions
  38346. var lp = positions.length;
  38347. var l = lp / 3;
  38348. for (var p = 0; p < lp; p++) {
  38349. positions[lp + p] = positions[p];
  38350. }
  38351. // indices
  38352. for (i = 0; i < li; i += 3) {
  38353. indices[i + li] = indices[i + 2] + l;
  38354. indices[i + 1 + li] = indices[i + 1] + l;
  38355. indices[i + 2 + li] = indices[i] + l;
  38356. }
  38357. // normals
  38358. for (n = 0; n < ln; n++) {
  38359. normals[ln + n] = -normals[n];
  38360. }
  38361. // uvs
  38362. var lu = uvs.length;
  38363. var u = 0;
  38364. for (u = 0; u < lu; u++) {
  38365. uvs[u + lu] = uvs[u];
  38366. }
  38367. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38368. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38369. u = 0;
  38370. for (i = 0; i < lu / 2; i++) {
  38371. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38372. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38373. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38374. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38375. u += 2;
  38376. }
  38377. break;
  38378. }
  38379. };
  38380. /**
  38381. * Applies VertexData created from the imported parameters to the geometry
  38382. * @param parsedVertexData the parsed data from an imported file
  38383. * @param geometry the geometry to apply the VertexData to
  38384. */
  38385. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38386. var vertexData = new VertexData();
  38387. // positions
  38388. var positions = parsedVertexData.positions;
  38389. if (positions) {
  38390. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38391. }
  38392. // normals
  38393. var normals = parsedVertexData.normals;
  38394. if (normals) {
  38395. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38396. }
  38397. // tangents
  38398. var tangents = parsedVertexData.tangents;
  38399. if (tangents) {
  38400. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38401. }
  38402. // uvs
  38403. var uvs = parsedVertexData.uvs;
  38404. if (uvs) {
  38405. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38406. }
  38407. // uv2s
  38408. var uv2s = parsedVertexData.uv2s;
  38409. if (uv2s) {
  38410. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38411. }
  38412. // uv3s
  38413. var uv3s = parsedVertexData.uv3s;
  38414. if (uv3s) {
  38415. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38416. }
  38417. // uv4s
  38418. var uv4s = parsedVertexData.uv4s;
  38419. if (uv4s) {
  38420. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38421. }
  38422. // uv5s
  38423. var uv5s = parsedVertexData.uv5s;
  38424. if (uv5s) {
  38425. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38426. }
  38427. // uv6s
  38428. var uv6s = parsedVertexData.uv6s;
  38429. if (uv6s) {
  38430. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38431. }
  38432. // colors
  38433. var colors = parsedVertexData.colors;
  38434. if (colors) {
  38435. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38436. }
  38437. // matricesIndices
  38438. var matricesIndices = parsedVertexData.matricesIndices;
  38439. if (matricesIndices) {
  38440. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38441. }
  38442. // matricesWeights
  38443. var matricesWeights = parsedVertexData.matricesWeights;
  38444. if (matricesWeights) {
  38445. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38446. }
  38447. // indices
  38448. var indices = parsedVertexData.indices;
  38449. if (indices) {
  38450. vertexData.indices = indices;
  38451. }
  38452. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38453. };
  38454. return VertexData;
  38455. }());
  38456. BABYLON.VertexData = VertexData;
  38457. })(BABYLON || (BABYLON = {}));
  38458. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38459. var BABYLON;
  38460. (function (BABYLON) {
  38461. /**
  38462. * Class used to store geometry data (vertex buffers + index buffer)
  38463. */
  38464. var Geometry = /** @class */ (function () {
  38465. /**
  38466. * Creates a new geometry
  38467. * @param id defines the unique ID
  38468. * @param scene defines the hosting scene
  38469. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38470. * @param updatable defines if geometry must be updatable (false by default)
  38471. * @param mesh defines the mesh that will be associated with the geometry
  38472. */
  38473. function Geometry(id, scene, vertexData, updatable, mesh) {
  38474. if (updatable === void 0) { updatable = false; }
  38475. if (mesh === void 0) { mesh = null; }
  38476. /**
  38477. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38478. */
  38479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38480. this._totalVertices = 0;
  38481. this._isDisposed = false;
  38482. this._indexBufferIsUpdatable = false;
  38483. this.id = id;
  38484. this._engine = scene.getEngine();
  38485. this._meshes = [];
  38486. this._scene = scene;
  38487. //Init vertex buffer cache
  38488. this._vertexBuffers = {};
  38489. this._indices = [];
  38490. this._updatable = updatable;
  38491. // vertexData
  38492. if (vertexData) {
  38493. this.setAllVerticesData(vertexData, updatable);
  38494. }
  38495. else {
  38496. this._totalVertices = 0;
  38497. this._indices = [];
  38498. }
  38499. if (this._engine.getCaps().vertexArrayObject) {
  38500. this._vertexArrayObjects = {};
  38501. }
  38502. // applyToMesh
  38503. if (mesh) {
  38504. if (mesh.getClassName() === "LinesMesh") {
  38505. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38506. this._updateExtend();
  38507. }
  38508. this.applyToMesh(mesh);
  38509. mesh.computeWorldMatrix(true);
  38510. }
  38511. }
  38512. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38513. /**
  38514. * 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
  38515. */
  38516. get: function () {
  38517. return this._boundingBias;
  38518. },
  38519. /**
  38520. * 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
  38521. */
  38522. set: function (value) {
  38523. if (this._boundingBias && this._boundingBias.equals(value)) {
  38524. return;
  38525. }
  38526. this._boundingBias = value.clone();
  38527. this._updateBoundingInfo(true, null);
  38528. },
  38529. enumerable: true,
  38530. configurable: true
  38531. });
  38532. /**
  38533. * Static function used to attach a new empty geometry to a mesh
  38534. * @param mesh defines the mesh to attach the geometry to
  38535. * @returns the new {BABYLON.Geometry}
  38536. */
  38537. Geometry.CreateGeometryForMesh = function (mesh) {
  38538. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38539. geometry.applyToMesh(mesh);
  38540. return geometry;
  38541. };
  38542. Object.defineProperty(Geometry.prototype, "extend", {
  38543. /**
  38544. * Gets the current extend of the geometry
  38545. */
  38546. get: function () {
  38547. return this._extend;
  38548. },
  38549. enumerable: true,
  38550. configurable: true
  38551. });
  38552. /**
  38553. * Gets the hosting scene
  38554. * @returns the hosting {BABYLON.Scene}
  38555. */
  38556. Geometry.prototype.getScene = function () {
  38557. return this._scene;
  38558. };
  38559. /**
  38560. * Gets the hosting engine
  38561. * @returns the hosting {BABYLON.Engine}
  38562. */
  38563. Geometry.prototype.getEngine = function () {
  38564. return this._engine;
  38565. };
  38566. /**
  38567. * Defines if the geometry is ready to use
  38568. * @returns true if the geometry is ready to be used
  38569. */
  38570. Geometry.prototype.isReady = function () {
  38571. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38572. };
  38573. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38574. /**
  38575. * Gets a value indicating that the geometry should not be serialized
  38576. */
  38577. get: function () {
  38578. for (var index = 0; index < this._meshes.length; index++) {
  38579. if (!this._meshes[index].doNotSerialize) {
  38580. return false;
  38581. }
  38582. }
  38583. return true;
  38584. },
  38585. enumerable: true,
  38586. configurable: true
  38587. });
  38588. /** @hidden */
  38589. Geometry.prototype._rebuild = function () {
  38590. if (this._vertexArrayObjects) {
  38591. this._vertexArrayObjects = {};
  38592. }
  38593. // Index buffer
  38594. if (this._meshes.length !== 0 && this._indices) {
  38595. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38596. }
  38597. // Vertex buffers
  38598. for (var key in this._vertexBuffers) {
  38599. var vertexBuffer = this._vertexBuffers[key];
  38600. vertexBuffer._rebuild();
  38601. }
  38602. };
  38603. /**
  38604. * Affects all gemetry data in one call
  38605. * @param vertexData defines the geometry data
  38606. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38607. */
  38608. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38609. vertexData.applyToGeometry(this, updatable);
  38610. this.notifyUpdate();
  38611. };
  38612. /**
  38613. * Set specific vertex data
  38614. * @param kind defines the data kind (Position, normal, etc...)
  38615. * @param data defines the vertex data to use
  38616. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38617. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38618. */
  38619. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38620. if (updatable === void 0) { updatable = false; }
  38621. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38622. this.setVerticesBuffer(buffer);
  38623. };
  38624. /**
  38625. * Removes a specific vertex data
  38626. * @param kind defines the data kind (Position, normal, etc...)
  38627. */
  38628. Geometry.prototype.removeVerticesData = function (kind) {
  38629. if (this._vertexBuffers[kind]) {
  38630. this._vertexBuffers[kind].dispose();
  38631. delete this._vertexBuffers[kind];
  38632. }
  38633. };
  38634. /**
  38635. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38636. * @param buffer defines the vertex buffer to use
  38637. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38638. */
  38639. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38640. if (totalVertices === void 0) { totalVertices = null; }
  38641. var kind = buffer.getKind();
  38642. if (this._vertexBuffers[kind]) {
  38643. this._vertexBuffers[kind].dispose();
  38644. }
  38645. this._vertexBuffers[kind] = buffer;
  38646. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38647. var data = buffer.getData();
  38648. if (totalVertices != null) {
  38649. this._totalVertices = totalVertices;
  38650. }
  38651. else {
  38652. if (data != null) {
  38653. this._totalVertices = data.length / (buffer.byteStride / 4);
  38654. }
  38655. }
  38656. this._updateExtend(data);
  38657. this._resetPointsArrayCache();
  38658. var meshes = this._meshes;
  38659. var numOfMeshes = meshes.length;
  38660. for (var index = 0; index < numOfMeshes; index++) {
  38661. var mesh = meshes[index];
  38662. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38663. mesh._createGlobalSubMesh(false);
  38664. mesh.computeWorldMatrix(true);
  38665. }
  38666. }
  38667. this.notifyUpdate(kind);
  38668. if (this._vertexArrayObjects) {
  38669. this._disposeVertexArrayObjects();
  38670. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38671. }
  38672. };
  38673. /**
  38674. * Update a specific vertex buffer
  38675. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38676. * It will do nothing if the buffer is not updatable
  38677. * @param kind defines the data kind (Position, normal, etc...)
  38678. * @param data defines the data to use
  38679. * @param offset defines the offset in the target buffer where to store the data
  38680. * @param useBytes set to true if the offset is in bytes
  38681. */
  38682. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38683. if (useBytes === void 0) { useBytes = false; }
  38684. var vertexBuffer = this.getVertexBuffer(kind);
  38685. if (!vertexBuffer) {
  38686. return;
  38687. }
  38688. vertexBuffer.updateDirectly(data, offset, useBytes);
  38689. this.notifyUpdate(kind);
  38690. };
  38691. /**
  38692. * Update a specific vertex buffer
  38693. * This function will create a new buffer if the current one is not updatable
  38694. * @param kind defines the data kind (Position, normal, etc...)
  38695. * @param data defines the data to use
  38696. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38697. */
  38698. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38699. if (updateExtends === void 0) { updateExtends = false; }
  38700. var vertexBuffer = this.getVertexBuffer(kind);
  38701. if (!vertexBuffer) {
  38702. return;
  38703. }
  38704. vertexBuffer.update(data);
  38705. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38706. this._updateBoundingInfo(updateExtends, data);
  38707. }
  38708. this.notifyUpdate(kind);
  38709. };
  38710. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38711. if (updateExtends) {
  38712. this._updateExtend(data);
  38713. }
  38714. var meshes = this._meshes;
  38715. var numOfMeshes = meshes.length;
  38716. this._resetPointsArrayCache();
  38717. for (var index = 0; index < numOfMeshes; index++) {
  38718. var mesh = meshes[index];
  38719. if (updateExtends) {
  38720. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38721. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38722. var subMesh = mesh.subMeshes[subIndex];
  38723. subMesh.refreshBoundingInfo();
  38724. }
  38725. }
  38726. }
  38727. };
  38728. /** @hidden */
  38729. Geometry.prototype._bind = function (effect, indexToBind) {
  38730. if (!effect) {
  38731. return;
  38732. }
  38733. if (indexToBind === undefined) {
  38734. indexToBind = this._indexBuffer;
  38735. }
  38736. var vbs = this.getVertexBuffers();
  38737. if (!vbs) {
  38738. return;
  38739. }
  38740. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38741. this._engine.bindBuffers(vbs, indexToBind, effect);
  38742. return;
  38743. }
  38744. // Using VAO
  38745. if (!this._vertexArrayObjects[effect.key]) {
  38746. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38747. }
  38748. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38749. };
  38750. /**
  38751. * Gets total number of vertices
  38752. * @returns the total number of vertices
  38753. */
  38754. Geometry.prototype.getTotalVertices = function () {
  38755. if (!this.isReady()) {
  38756. return 0;
  38757. }
  38758. return this._totalVertices;
  38759. };
  38760. /**
  38761. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38762. * @param kind defines the data kind (Position, normal, etc...)
  38763. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38764. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38765. * @returns a float array containing vertex data
  38766. */
  38767. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38768. var vertexBuffer = this.getVertexBuffer(kind);
  38769. if (!vertexBuffer) {
  38770. return null;
  38771. }
  38772. var data = vertexBuffer.getData();
  38773. if (!data) {
  38774. return null;
  38775. }
  38776. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38777. var count = this._totalVertices * vertexBuffer.getSize();
  38778. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38779. var copy_1 = new Array(count);
  38780. vertexBuffer.forEach(count, function (value, index) {
  38781. copy_1[index] = value;
  38782. });
  38783. return copy_1;
  38784. }
  38785. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38786. if (data instanceof Array) {
  38787. var offset = vertexBuffer.byteOffset / 4;
  38788. return BABYLON.Tools.Slice(data, offset, offset + count);
  38789. }
  38790. else if (data instanceof ArrayBuffer) {
  38791. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38792. }
  38793. else {
  38794. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38795. }
  38796. }
  38797. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38798. return BABYLON.Tools.Slice(data);
  38799. }
  38800. return data;
  38801. };
  38802. /**
  38803. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38804. * @param kind defines the data kind (Position, normal, etc...)
  38805. * @returns true if the vertex buffer with the specified kind is updatable
  38806. */
  38807. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38808. var vb = this._vertexBuffers[kind];
  38809. if (!vb) {
  38810. return false;
  38811. }
  38812. return vb.isUpdatable();
  38813. };
  38814. /**
  38815. * Gets a specific vertex buffer
  38816. * @param kind defines the data kind (Position, normal, etc...)
  38817. * @returns a {BABYLON.VertexBuffer}
  38818. */
  38819. Geometry.prototype.getVertexBuffer = function (kind) {
  38820. if (!this.isReady()) {
  38821. return null;
  38822. }
  38823. return this._vertexBuffers[kind];
  38824. };
  38825. /**
  38826. * Returns all vertex buffers
  38827. * @return an object holding all vertex buffers indexed by kind
  38828. */
  38829. Geometry.prototype.getVertexBuffers = function () {
  38830. if (!this.isReady()) {
  38831. return null;
  38832. }
  38833. return this._vertexBuffers;
  38834. };
  38835. /**
  38836. * Gets a boolean indicating if specific vertex buffer is present
  38837. * @param kind defines the data kind (Position, normal, etc...)
  38838. * @returns true if data is present
  38839. */
  38840. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38841. if (!this._vertexBuffers) {
  38842. if (this._delayInfo) {
  38843. return this._delayInfo.indexOf(kind) !== -1;
  38844. }
  38845. return false;
  38846. }
  38847. return this._vertexBuffers[kind] !== undefined;
  38848. };
  38849. /**
  38850. * Gets a list of all attached data kinds (Position, normal, etc...)
  38851. * @returns a list of string containing all kinds
  38852. */
  38853. Geometry.prototype.getVerticesDataKinds = function () {
  38854. var result = [];
  38855. var kind;
  38856. if (!this._vertexBuffers && this._delayInfo) {
  38857. for (kind in this._delayInfo) {
  38858. result.push(kind);
  38859. }
  38860. }
  38861. else {
  38862. for (kind in this._vertexBuffers) {
  38863. result.push(kind);
  38864. }
  38865. }
  38866. return result;
  38867. };
  38868. /**
  38869. * Update index buffer
  38870. * @param indices defines the indices to store in the index buffer
  38871. * @param offset defines the offset in the target buffer where to store the data
  38872. */
  38873. Geometry.prototype.updateIndices = function (indices, offset) {
  38874. if (!this._indexBuffer) {
  38875. return;
  38876. }
  38877. if (!this._indexBufferIsUpdatable) {
  38878. this.setIndices(indices, null, true);
  38879. }
  38880. else {
  38881. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38882. }
  38883. };
  38884. /**
  38885. * Creates a new index buffer
  38886. * @param indices defines the indices to store in the index buffer
  38887. * @param totalVertices defines the total number of vertices (could be null)
  38888. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38889. */
  38890. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38891. if (totalVertices === void 0) { totalVertices = null; }
  38892. if (updatable === void 0) { updatable = false; }
  38893. if (this._indexBuffer) {
  38894. this._engine._releaseBuffer(this._indexBuffer);
  38895. }
  38896. this._disposeVertexArrayObjects();
  38897. this._indices = indices;
  38898. this._indexBufferIsUpdatable = updatable;
  38899. if (this._meshes.length !== 0 && this._indices) {
  38900. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38901. }
  38902. if (totalVertices != undefined) { // including null and undefined
  38903. this._totalVertices = totalVertices;
  38904. }
  38905. var meshes = this._meshes;
  38906. var numOfMeshes = meshes.length;
  38907. for (var index = 0; index < numOfMeshes; index++) {
  38908. meshes[index]._createGlobalSubMesh(true);
  38909. }
  38910. this.notifyUpdate();
  38911. };
  38912. /**
  38913. * Return the total number of indices
  38914. * @returns the total number of indices
  38915. */
  38916. Geometry.prototype.getTotalIndices = function () {
  38917. if (!this.isReady()) {
  38918. return 0;
  38919. }
  38920. return this._indices.length;
  38921. };
  38922. /**
  38923. * Gets the index buffer array
  38924. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38925. * @returns the index buffer array
  38926. */
  38927. Geometry.prototype.getIndices = function (copyWhenShared) {
  38928. if (!this.isReady()) {
  38929. return null;
  38930. }
  38931. var orig = this._indices;
  38932. if (!copyWhenShared || this._meshes.length === 1) {
  38933. return orig;
  38934. }
  38935. else {
  38936. var len = orig.length;
  38937. var copy = [];
  38938. for (var i = 0; i < len; i++) {
  38939. copy.push(orig[i]);
  38940. }
  38941. return copy;
  38942. }
  38943. };
  38944. /**
  38945. * Gets the index buffer
  38946. * @return the index buffer
  38947. */
  38948. Geometry.prototype.getIndexBuffer = function () {
  38949. if (!this.isReady()) {
  38950. return null;
  38951. }
  38952. return this._indexBuffer;
  38953. };
  38954. /** @hidden */
  38955. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38956. if (effect === void 0) { effect = null; }
  38957. if (!effect || !this._vertexArrayObjects) {
  38958. return;
  38959. }
  38960. if (this._vertexArrayObjects[effect.key]) {
  38961. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38962. delete this._vertexArrayObjects[effect.key];
  38963. }
  38964. };
  38965. /**
  38966. * Release the associated resources for a specific mesh
  38967. * @param mesh defines the source mesh
  38968. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38969. */
  38970. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38971. var meshes = this._meshes;
  38972. var index = meshes.indexOf(mesh);
  38973. if (index === -1) {
  38974. return;
  38975. }
  38976. meshes.splice(index, 1);
  38977. mesh._geometry = null;
  38978. if (meshes.length === 0 && shouldDispose) {
  38979. this.dispose();
  38980. }
  38981. };
  38982. /**
  38983. * Apply current geometry to a given mesh
  38984. * @param mesh defines the mesh to apply geometry to
  38985. */
  38986. Geometry.prototype.applyToMesh = function (mesh) {
  38987. if (mesh._geometry === this) {
  38988. return;
  38989. }
  38990. var previousGeometry = mesh._geometry;
  38991. if (previousGeometry) {
  38992. previousGeometry.releaseForMesh(mesh);
  38993. }
  38994. var meshes = this._meshes;
  38995. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38996. mesh._geometry = this;
  38997. this._scene.pushGeometry(this);
  38998. meshes.push(mesh);
  38999. if (this.isReady()) {
  39000. this._applyToMesh(mesh);
  39001. }
  39002. else {
  39003. mesh._boundingInfo = this._boundingInfo;
  39004. }
  39005. };
  39006. Geometry.prototype._updateExtend = function (data) {
  39007. if (data === void 0) { data = null; }
  39008. if (!data) {
  39009. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39010. }
  39011. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39012. };
  39013. Geometry.prototype._applyToMesh = function (mesh) {
  39014. var numOfMeshes = this._meshes.length;
  39015. // vertexBuffers
  39016. for (var kind in this._vertexBuffers) {
  39017. if (numOfMeshes === 1) {
  39018. this._vertexBuffers[kind].create();
  39019. }
  39020. var buffer = this._vertexBuffers[kind].getBuffer();
  39021. if (buffer)
  39022. buffer.references = numOfMeshes;
  39023. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39024. if (!this._extend) {
  39025. this._updateExtend();
  39026. }
  39027. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39028. mesh._createGlobalSubMesh(false);
  39029. //bounding info was just created again, world matrix should be applied again.
  39030. mesh._updateBoundingInfo();
  39031. }
  39032. }
  39033. // indexBuffer
  39034. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39035. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39036. }
  39037. if (this._indexBuffer) {
  39038. this._indexBuffer.references = numOfMeshes;
  39039. }
  39040. };
  39041. Geometry.prototype.notifyUpdate = function (kind) {
  39042. if (this.onGeometryUpdated) {
  39043. this.onGeometryUpdated(this, kind);
  39044. }
  39045. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39046. var mesh = _a[_i];
  39047. mesh._markSubMeshesAsAttributesDirty();
  39048. }
  39049. };
  39050. /**
  39051. * Load the geometry if it was flagged as delay loaded
  39052. * @param scene defines the hosting scene
  39053. * @param onLoaded defines a callback called when the geometry is loaded
  39054. */
  39055. Geometry.prototype.load = function (scene, onLoaded) {
  39056. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39057. return;
  39058. }
  39059. if (this.isReady()) {
  39060. if (onLoaded) {
  39061. onLoaded();
  39062. }
  39063. return;
  39064. }
  39065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39066. this._queueLoad(scene, onLoaded);
  39067. };
  39068. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39069. var _this = this;
  39070. if (!this.delayLoadingFile) {
  39071. return;
  39072. }
  39073. scene._addPendingData(this);
  39074. scene._loadFile(this.delayLoadingFile, function (data) {
  39075. if (!_this._delayLoadingFunction) {
  39076. return;
  39077. }
  39078. _this._delayLoadingFunction(JSON.parse(data), _this);
  39079. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39080. _this._delayInfo = [];
  39081. scene._removePendingData(_this);
  39082. var meshes = _this._meshes;
  39083. var numOfMeshes = meshes.length;
  39084. for (var index = 0; index < numOfMeshes; index++) {
  39085. _this._applyToMesh(meshes[index]);
  39086. }
  39087. if (onLoaded) {
  39088. onLoaded();
  39089. }
  39090. }, undefined, true);
  39091. };
  39092. /**
  39093. * Invert the geometry to move from a right handed system to a left handed one.
  39094. */
  39095. Geometry.prototype.toLeftHanded = function () {
  39096. // Flip faces
  39097. var tIndices = this.getIndices(false);
  39098. if (tIndices != null && tIndices.length > 0) {
  39099. for (var i = 0; i < tIndices.length; i += 3) {
  39100. var tTemp = tIndices[i + 0];
  39101. tIndices[i + 0] = tIndices[i + 2];
  39102. tIndices[i + 2] = tTemp;
  39103. }
  39104. this.setIndices(tIndices);
  39105. }
  39106. // Negate position.z
  39107. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39108. if (tPositions != null && tPositions.length > 0) {
  39109. for (var i = 0; i < tPositions.length; i += 3) {
  39110. tPositions[i + 2] = -tPositions[i + 2];
  39111. }
  39112. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39113. }
  39114. // Negate normal.z
  39115. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39116. if (tNormals != null && tNormals.length > 0) {
  39117. for (var i = 0; i < tNormals.length; i += 3) {
  39118. tNormals[i + 2] = -tNormals[i + 2];
  39119. }
  39120. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39121. }
  39122. };
  39123. // Cache
  39124. /** @hidden */
  39125. Geometry.prototype._resetPointsArrayCache = function () {
  39126. this._positions = null;
  39127. };
  39128. /** @hidden */
  39129. Geometry.prototype._generatePointsArray = function () {
  39130. if (this._positions)
  39131. return true;
  39132. this._positions = [];
  39133. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39134. if (!data) {
  39135. return false;
  39136. }
  39137. for (var index = 0; index < data.length; index += 3) {
  39138. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39139. }
  39140. return true;
  39141. };
  39142. /**
  39143. * Gets a value indicating if the geometry is disposed
  39144. * @returns true if the geometry was disposed
  39145. */
  39146. Geometry.prototype.isDisposed = function () {
  39147. return this._isDisposed;
  39148. };
  39149. Geometry.prototype._disposeVertexArrayObjects = function () {
  39150. if (this._vertexArrayObjects) {
  39151. for (var kind in this._vertexArrayObjects) {
  39152. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39153. }
  39154. this._vertexArrayObjects = {};
  39155. }
  39156. };
  39157. /**
  39158. * Free all associated resources
  39159. */
  39160. Geometry.prototype.dispose = function () {
  39161. var meshes = this._meshes;
  39162. var numOfMeshes = meshes.length;
  39163. var index;
  39164. for (index = 0; index < numOfMeshes; index++) {
  39165. this.releaseForMesh(meshes[index]);
  39166. }
  39167. this._meshes = [];
  39168. this._disposeVertexArrayObjects();
  39169. for (var kind in this._vertexBuffers) {
  39170. this._vertexBuffers[kind].dispose();
  39171. }
  39172. this._vertexBuffers = {};
  39173. this._totalVertices = 0;
  39174. if (this._indexBuffer) {
  39175. this._engine._releaseBuffer(this._indexBuffer);
  39176. }
  39177. this._indexBuffer = null;
  39178. this._indices = [];
  39179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39180. this.delayLoadingFile = null;
  39181. this._delayLoadingFunction = null;
  39182. this._delayInfo = [];
  39183. this._boundingInfo = null;
  39184. this._scene.removeGeometry(this);
  39185. this._isDisposed = true;
  39186. };
  39187. /**
  39188. * Clone the current geometry into a new geometry
  39189. * @param id defines the unique ID of the new geometry
  39190. * @returns a new geometry object
  39191. */
  39192. Geometry.prototype.copy = function (id) {
  39193. var vertexData = new BABYLON.VertexData();
  39194. vertexData.indices = [];
  39195. var indices = this.getIndices();
  39196. if (indices) {
  39197. for (var index = 0; index < indices.length; index++) {
  39198. vertexData.indices.push(indices[index]);
  39199. }
  39200. }
  39201. var updatable = false;
  39202. var stopChecking = false;
  39203. var kind;
  39204. for (kind in this._vertexBuffers) {
  39205. // using slice() to make a copy of the array and not just reference it
  39206. var data = this.getVerticesData(kind);
  39207. if (data instanceof Float32Array) {
  39208. vertexData.set(new Float32Array(data), kind);
  39209. }
  39210. else {
  39211. vertexData.set(data.slice(0), kind);
  39212. }
  39213. if (!stopChecking) {
  39214. var vb = this.getVertexBuffer(kind);
  39215. if (vb) {
  39216. updatable = vb.isUpdatable();
  39217. stopChecking = !updatable;
  39218. }
  39219. }
  39220. }
  39221. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39222. geometry.delayLoadState = this.delayLoadState;
  39223. geometry.delayLoadingFile = this.delayLoadingFile;
  39224. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39225. for (kind in this._delayInfo) {
  39226. geometry._delayInfo = geometry._delayInfo || [];
  39227. geometry._delayInfo.push(kind);
  39228. }
  39229. // Bounding info
  39230. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39231. return geometry;
  39232. };
  39233. /**
  39234. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39235. * @return a JSON representation of the current geometry data (without the vertices data)
  39236. */
  39237. Geometry.prototype.serialize = function () {
  39238. var serializationObject = {};
  39239. serializationObject.id = this.id;
  39240. serializationObject.updatable = this._updatable;
  39241. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39242. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39243. }
  39244. return serializationObject;
  39245. };
  39246. Geometry.prototype.toNumberArray = function (origin) {
  39247. if (Array.isArray(origin)) {
  39248. return origin;
  39249. }
  39250. else {
  39251. return Array.prototype.slice.call(origin);
  39252. }
  39253. };
  39254. /**
  39255. * Serialize all vertices data into a JSON oject
  39256. * @returns a JSON representation of the current geometry data
  39257. */
  39258. Geometry.prototype.serializeVerticeData = function () {
  39259. var serializationObject = this.serialize();
  39260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39261. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39262. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39263. serializationObject.positions._updatable = true;
  39264. }
  39265. }
  39266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39267. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39268. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39269. serializationObject.normals._updatable = true;
  39270. }
  39271. }
  39272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39273. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39274. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39275. serializationObject.tangets._updatable = true;
  39276. }
  39277. }
  39278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39279. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39280. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39281. serializationObject.uvs._updatable = true;
  39282. }
  39283. }
  39284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39285. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39286. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39287. serializationObject.uv2s._updatable = true;
  39288. }
  39289. }
  39290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39291. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39292. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39293. serializationObject.uv3s._updatable = true;
  39294. }
  39295. }
  39296. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39297. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39298. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39299. serializationObject.uv4s._updatable = true;
  39300. }
  39301. }
  39302. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39303. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39304. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39305. serializationObject.uv5s._updatable = true;
  39306. }
  39307. }
  39308. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39309. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39310. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39311. serializationObject.uv6s._updatable = true;
  39312. }
  39313. }
  39314. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39315. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39316. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39317. serializationObject.colors._updatable = true;
  39318. }
  39319. }
  39320. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39321. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39322. serializationObject.matricesIndices._isExpanded = true;
  39323. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39324. serializationObject.matricesIndices._updatable = true;
  39325. }
  39326. }
  39327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39328. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39329. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39330. serializationObject.matricesWeights._updatable = true;
  39331. }
  39332. }
  39333. serializationObject.indices = this.toNumberArray(this.getIndices());
  39334. return serializationObject;
  39335. };
  39336. // Statics
  39337. /**
  39338. * Extracts a clone of a mesh geometry
  39339. * @param mesh defines the source mesh
  39340. * @param id defines the unique ID of the new geometry object
  39341. * @returns the new geometry object
  39342. */
  39343. Geometry.ExtractFromMesh = function (mesh, id) {
  39344. var geometry = mesh._geometry;
  39345. if (!geometry) {
  39346. return null;
  39347. }
  39348. return geometry.copy(id);
  39349. };
  39350. /**
  39351. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39352. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39353. * Be aware Math.random() could cause collisions, but:
  39354. * "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"
  39355. * @returns a string containing a new GUID
  39356. */
  39357. Geometry.RandomId = function () {
  39358. return BABYLON.Tools.RandomId();
  39359. };
  39360. /** @hidden */
  39361. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39362. var scene = mesh.getScene();
  39363. // Geometry
  39364. var geometryId = parsedGeometry.geometryId;
  39365. if (geometryId) {
  39366. var geometry = scene.getGeometryByID(geometryId);
  39367. if (geometry) {
  39368. geometry.applyToMesh(mesh);
  39369. }
  39370. }
  39371. else if (parsedGeometry instanceof ArrayBuffer) {
  39372. var binaryInfo = mesh._binaryInfo;
  39373. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39374. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39375. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39376. }
  39377. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39378. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39379. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39380. }
  39381. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39382. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39384. }
  39385. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39386. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39387. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39388. }
  39389. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39390. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39391. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39392. }
  39393. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39394. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39395. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39396. }
  39397. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39398. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39399. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39400. }
  39401. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39402. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39403. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39404. }
  39405. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39406. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39407. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39408. }
  39409. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39410. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39411. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39412. }
  39413. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39414. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39416. }
  39417. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39418. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39420. }
  39421. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39422. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39423. mesh.setIndices(indicesData, null);
  39424. }
  39425. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39426. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39427. mesh.subMeshes = [];
  39428. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39429. var materialIndex = subMeshesData[(i * 5) + 0];
  39430. var verticesStart = subMeshesData[(i * 5) + 1];
  39431. var verticesCount = subMeshesData[(i * 5) + 2];
  39432. var indexStart = subMeshesData[(i * 5) + 3];
  39433. var indexCount = subMeshesData[(i * 5) + 4];
  39434. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39435. }
  39436. }
  39437. }
  39438. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39439. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39440. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39441. if (parsedGeometry.tangents) {
  39442. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39443. }
  39444. if (parsedGeometry.uvs) {
  39445. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39446. }
  39447. if (parsedGeometry.uvs2) {
  39448. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39449. }
  39450. if (parsedGeometry.uvs3) {
  39451. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39452. }
  39453. if (parsedGeometry.uvs4) {
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39455. }
  39456. if (parsedGeometry.uvs5) {
  39457. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39458. }
  39459. if (parsedGeometry.uvs6) {
  39460. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39461. }
  39462. if (parsedGeometry.colors) {
  39463. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39464. }
  39465. if (parsedGeometry.matricesIndices) {
  39466. if (!parsedGeometry.matricesIndices._isExpanded) {
  39467. var floatIndices = [];
  39468. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39469. var matricesIndex = parsedGeometry.matricesIndices[i];
  39470. floatIndices.push(matricesIndex & 0x000000FF);
  39471. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39472. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39473. floatIndices.push(matricesIndex >> 24);
  39474. }
  39475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39476. }
  39477. else {
  39478. delete parsedGeometry.matricesIndices._isExpanded;
  39479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39480. }
  39481. }
  39482. if (parsedGeometry.matricesIndicesExtra) {
  39483. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39484. var floatIndices = [];
  39485. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39486. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39487. floatIndices.push(matricesIndex & 0x000000FF);
  39488. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39489. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39490. floatIndices.push(matricesIndex >> 24);
  39491. }
  39492. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39493. }
  39494. else {
  39495. delete parsedGeometry.matricesIndices._isExpanded;
  39496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39497. }
  39498. }
  39499. if (parsedGeometry.matricesWeights) {
  39500. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39502. }
  39503. if (parsedGeometry.matricesWeightsExtra) {
  39504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39505. }
  39506. mesh.setIndices(parsedGeometry.indices, null);
  39507. }
  39508. // SubMeshes
  39509. if (parsedGeometry.subMeshes) {
  39510. mesh.subMeshes = [];
  39511. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39512. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39513. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39514. }
  39515. }
  39516. // Flat shading
  39517. if (mesh._shouldGenerateFlatShading) {
  39518. mesh.convertToFlatShadedMesh();
  39519. delete mesh._shouldGenerateFlatShading;
  39520. }
  39521. // Update
  39522. mesh.computeWorldMatrix(true);
  39523. // Octree
  39524. var sceneOctree = scene.selectionOctree;
  39525. if (sceneOctree !== undefined && sceneOctree !== null) {
  39526. sceneOctree.addMesh(mesh);
  39527. }
  39528. };
  39529. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39530. var epsilon = 1e-3;
  39531. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39532. return;
  39533. }
  39534. var noInfluenceBoneIndex = 0.0;
  39535. if (parsedGeometry.skeletonId > -1) {
  39536. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39537. if (!skeleton) {
  39538. return;
  39539. }
  39540. noInfluenceBoneIndex = skeleton.bones.length;
  39541. }
  39542. else {
  39543. return;
  39544. }
  39545. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39546. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39547. var matricesWeights = parsedGeometry.matricesWeights;
  39548. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39549. var influencers = parsedGeometry.numBoneInfluencer;
  39550. var size = matricesWeights.length;
  39551. for (var i = 0; i < size; i += 4) {
  39552. var weight = 0.0;
  39553. var firstZeroWeight = -1;
  39554. for (var j = 0; j < 4; j++) {
  39555. var w = matricesWeights[i + j];
  39556. weight += w;
  39557. if (w < epsilon && firstZeroWeight < 0) {
  39558. firstZeroWeight = j;
  39559. }
  39560. }
  39561. if (matricesWeightsExtra) {
  39562. for (var j = 0; j < 4; j++) {
  39563. var w = matricesWeightsExtra[i + j];
  39564. weight += w;
  39565. if (w < epsilon && firstZeroWeight < 0) {
  39566. firstZeroWeight = j + 4;
  39567. }
  39568. }
  39569. }
  39570. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39571. firstZeroWeight = influencers - 1;
  39572. }
  39573. if (weight > epsilon) {
  39574. var mweight = 1.0 / weight;
  39575. for (var j = 0; j < 4; j++) {
  39576. matricesWeights[i + j] *= mweight;
  39577. }
  39578. if (matricesWeightsExtra) {
  39579. for (var j = 0; j < 4; j++) {
  39580. matricesWeightsExtra[i + j] *= mweight;
  39581. }
  39582. }
  39583. }
  39584. else {
  39585. if (firstZeroWeight >= 4) {
  39586. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39587. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39588. }
  39589. else {
  39590. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39591. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39592. }
  39593. }
  39594. }
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39596. if (parsedGeometry.matricesWeightsExtra) {
  39597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39598. }
  39599. };
  39600. /**
  39601. * Create a new geometry from persisted data (Using .babylon file format)
  39602. * @param parsedVertexData defines the persisted data
  39603. * @param scene defines the hosting scene
  39604. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39605. * @returns the new geometry object
  39606. */
  39607. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39608. if (scene.getGeometryByID(parsedVertexData.id)) {
  39609. return null; // null since geometry could be something else than a box...
  39610. }
  39611. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39612. if (BABYLON.Tags) {
  39613. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39614. }
  39615. if (parsedVertexData.delayLoadingFile) {
  39616. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39617. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39618. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39619. geometry._delayInfo = [];
  39620. if (parsedVertexData.hasUVs) {
  39621. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39622. }
  39623. if (parsedVertexData.hasUVs2) {
  39624. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39625. }
  39626. if (parsedVertexData.hasUVs3) {
  39627. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39628. }
  39629. if (parsedVertexData.hasUVs4) {
  39630. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39631. }
  39632. if (parsedVertexData.hasUVs5) {
  39633. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39634. }
  39635. if (parsedVertexData.hasUVs6) {
  39636. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39637. }
  39638. if (parsedVertexData.hasColors) {
  39639. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39640. }
  39641. if (parsedVertexData.hasMatricesIndices) {
  39642. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39643. }
  39644. if (parsedVertexData.hasMatricesWeights) {
  39645. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39646. }
  39647. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39648. }
  39649. else {
  39650. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39651. }
  39652. scene.pushGeometry(geometry, true);
  39653. return geometry;
  39654. };
  39655. return Geometry;
  39656. }());
  39657. BABYLON.Geometry = Geometry;
  39658. // Primitives
  39659. /// Abstract class
  39660. /**
  39661. * Abstract class used to provide common services for all typed geometries
  39662. * @hidden
  39663. */
  39664. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39665. __extends(_PrimitiveGeometry, _super);
  39666. /**
  39667. * Creates a new typed geometry
  39668. * @param id defines the unique ID of the geometry
  39669. * @param scene defines the hosting scene
  39670. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39671. * @param mesh defines the hosting mesh (can be null)
  39672. */
  39673. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39674. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39675. if (mesh === void 0) { mesh = null; }
  39676. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39677. _this._canBeRegenerated = _canBeRegenerated;
  39678. _this._beingRegenerated = true;
  39679. _this.regenerate();
  39680. _this._beingRegenerated = false;
  39681. return _this;
  39682. }
  39683. /**
  39684. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39685. * @returns true if the geometry can be regenerated
  39686. */
  39687. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39688. return this._canBeRegenerated;
  39689. };
  39690. /**
  39691. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39692. */
  39693. _PrimitiveGeometry.prototype.regenerate = function () {
  39694. if (!this._canBeRegenerated) {
  39695. return;
  39696. }
  39697. this._beingRegenerated = true;
  39698. this.setAllVerticesData(this._regenerateVertexData(), false);
  39699. this._beingRegenerated = false;
  39700. };
  39701. /**
  39702. * Clone the geometry
  39703. * @param id defines the unique ID of the new geometry
  39704. * @returns the new geometry
  39705. */
  39706. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39707. return _super.prototype.copy.call(this, id);
  39708. };
  39709. // overrides
  39710. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39711. if (!this._beingRegenerated) {
  39712. return;
  39713. }
  39714. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39715. };
  39716. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39717. if (!this._beingRegenerated) {
  39718. return;
  39719. }
  39720. _super.prototype.setVerticesData.call(this, kind, data, false);
  39721. };
  39722. // to override
  39723. /** @hidden */
  39724. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39725. throw new Error("Abstract method");
  39726. };
  39727. _PrimitiveGeometry.prototype.copy = function (id) {
  39728. throw new Error("Must be overriden in sub-classes.");
  39729. };
  39730. _PrimitiveGeometry.prototype.serialize = function () {
  39731. var serializationObject = _super.prototype.serialize.call(this);
  39732. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39733. return serializationObject;
  39734. };
  39735. return _PrimitiveGeometry;
  39736. }(Geometry));
  39737. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39738. /**
  39739. * Creates a ribbon geometry
  39740. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39741. */
  39742. var RibbonGeometry = /** @class */ (function (_super) {
  39743. __extends(RibbonGeometry, _super);
  39744. /**
  39745. * Creates a ribbon geometry
  39746. * @param id defines the unique ID of the geometry
  39747. * @param scene defines the hosting scene
  39748. * @param pathArray defines the array of paths to use
  39749. * @param closeArray defines if the last path and the first path must be joined
  39750. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39751. * @param offset defines the offset between points
  39752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39753. * @param mesh defines the hosting mesh (can be null)
  39754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39755. */
  39756. function RibbonGeometry(id, scene,
  39757. /**
  39758. * Defines the array of paths to use
  39759. */
  39760. pathArray,
  39761. /**
  39762. * Defines if the last and first points of each path in your pathArray must be joined
  39763. */
  39764. closeArray,
  39765. /**
  39766. * Defines if the last and first points of each path in your pathArray must be joined
  39767. */
  39768. closePath,
  39769. /**
  39770. * Defines the offset between points
  39771. */
  39772. offset, canBeRegenerated, mesh,
  39773. /**
  39774. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39775. */
  39776. side) {
  39777. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39779. _this.pathArray = pathArray;
  39780. _this.closeArray = closeArray;
  39781. _this.closePath = closePath;
  39782. _this.offset = offset;
  39783. _this.side = side;
  39784. return _this;
  39785. }
  39786. /** @hidden */
  39787. RibbonGeometry.prototype._regenerateVertexData = function () {
  39788. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39789. };
  39790. RibbonGeometry.prototype.copy = function (id) {
  39791. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39792. };
  39793. return RibbonGeometry;
  39794. }(_PrimitiveGeometry));
  39795. BABYLON.RibbonGeometry = RibbonGeometry;
  39796. /**
  39797. * Creates a box geometry
  39798. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39799. */
  39800. var BoxGeometry = /** @class */ (function (_super) {
  39801. __extends(BoxGeometry, _super);
  39802. /**
  39803. * Creates a box geometry
  39804. * @param id defines the unique ID of the geometry
  39805. * @param scene defines the hosting scene
  39806. * @param size defines the zise of the box (width, height and depth are the same)
  39807. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39808. * @param mesh defines the hosting mesh (can be null)
  39809. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39810. */
  39811. function BoxGeometry(id, scene,
  39812. /**
  39813. * Defines the zise of the box (width, height and depth are the same)
  39814. */
  39815. size, canBeRegenerated, mesh,
  39816. /**
  39817. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39818. */
  39819. side) {
  39820. if (mesh === void 0) { mesh = null; }
  39821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39822. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39823. _this.size = size;
  39824. _this.side = side;
  39825. return _this;
  39826. }
  39827. BoxGeometry.prototype._regenerateVertexData = function () {
  39828. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39829. };
  39830. BoxGeometry.prototype.copy = function (id) {
  39831. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39832. };
  39833. BoxGeometry.prototype.serialize = function () {
  39834. var serializationObject = _super.prototype.serialize.call(this);
  39835. serializationObject.size = this.size;
  39836. return serializationObject;
  39837. };
  39838. BoxGeometry.Parse = function (parsedBox, scene) {
  39839. if (scene.getGeometryByID(parsedBox.id)) {
  39840. return null; // null since geometry could be something else than a box...
  39841. }
  39842. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39843. if (BABYLON.Tags) {
  39844. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39845. }
  39846. scene.pushGeometry(box, true);
  39847. return box;
  39848. };
  39849. return BoxGeometry;
  39850. }(_PrimitiveGeometry));
  39851. BABYLON.BoxGeometry = BoxGeometry;
  39852. /**
  39853. * Creates a sphere geometry
  39854. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39855. */
  39856. var SphereGeometry = /** @class */ (function (_super) {
  39857. __extends(SphereGeometry, _super);
  39858. /**
  39859. * Create a new sphere geometry
  39860. * @param id defines the unique ID of the geometry
  39861. * @param scene defines the hosting scene
  39862. * @param segments defines the number of segments to use to create the sphere
  39863. * @param diameter defines the diameter of the sphere
  39864. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39865. * @param mesh defines the hosting mesh (can be null)
  39866. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39867. */
  39868. function SphereGeometry(id, scene,
  39869. /**
  39870. * Defines the number of segments to use to create the sphere
  39871. */
  39872. segments,
  39873. /**
  39874. * Defines the diameter of the sphere
  39875. */
  39876. diameter, canBeRegenerated, mesh,
  39877. /**
  39878. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39879. */
  39880. side) {
  39881. if (mesh === void 0) { mesh = null; }
  39882. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39883. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39884. _this.segments = segments;
  39885. _this.diameter = diameter;
  39886. _this.side = side;
  39887. return _this;
  39888. }
  39889. SphereGeometry.prototype._regenerateVertexData = function () {
  39890. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39891. };
  39892. SphereGeometry.prototype.copy = function (id) {
  39893. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39894. };
  39895. SphereGeometry.prototype.serialize = function () {
  39896. var serializationObject = _super.prototype.serialize.call(this);
  39897. serializationObject.segments = this.segments;
  39898. serializationObject.diameter = this.diameter;
  39899. return serializationObject;
  39900. };
  39901. SphereGeometry.Parse = function (parsedSphere, scene) {
  39902. if (scene.getGeometryByID(parsedSphere.id)) {
  39903. return null; // null since geometry could be something else than a sphere...
  39904. }
  39905. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39906. if (BABYLON.Tags) {
  39907. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39908. }
  39909. scene.pushGeometry(sphere, true);
  39910. return sphere;
  39911. };
  39912. return SphereGeometry;
  39913. }(_PrimitiveGeometry));
  39914. BABYLON.SphereGeometry = SphereGeometry;
  39915. /**
  39916. * Creates a disc geometry
  39917. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39918. */
  39919. var DiscGeometry = /** @class */ (function (_super) {
  39920. __extends(DiscGeometry, _super);
  39921. /**
  39922. * Creates a new disc geometry
  39923. * @param id defines the unique ID of the geometry
  39924. * @param scene defines the hosting scene
  39925. * @param radius defines the radius of the disc
  39926. * @param tessellation defines the tesselation factor to apply to the disc
  39927. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39928. * @param mesh defines the hosting mesh (can be null)
  39929. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39930. */
  39931. function DiscGeometry(id, scene,
  39932. /**
  39933. * Defines the radius of the disc
  39934. */
  39935. radius,
  39936. /**
  39937. * Defines the tesselation factor to apply to the disc
  39938. */
  39939. tessellation, canBeRegenerated, mesh,
  39940. /**
  39941. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39942. */
  39943. side) {
  39944. if (mesh === void 0) { mesh = null; }
  39945. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39946. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39947. _this.radius = radius;
  39948. _this.tessellation = tessellation;
  39949. _this.side = side;
  39950. return _this;
  39951. }
  39952. DiscGeometry.prototype._regenerateVertexData = function () {
  39953. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39954. };
  39955. DiscGeometry.prototype.copy = function (id) {
  39956. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39957. };
  39958. return DiscGeometry;
  39959. }(_PrimitiveGeometry));
  39960. BABYLON.DiscGeometry = DiscGeometry;
  39961. /**
  39962. * Creates a new cylinder geometry
  39963. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39964. */
  39965. var CylinderGeometry = /** @class */ (function (_super) {
  39966. __extends(CylinderGeometry, _super);
  39967. /**
  39968. * Creates a new cylinder geometry
  39969. * @param id defines the unique ID of the geometry
  39970. * @param scene defines the hosting scene
  39971. * @param height defines the height of the cylinder
  39972. * @param diameterTop defines the diameter of the cylinder's top cap
  39973. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39974. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39975. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39976. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39977. * @param mesh defines the hosting mesh (can be null)
  39978. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39979. */
  39980. function CylinderGeometry(id, scene,
  39981. /**
  39982. * Defines the height of the cylinder
  39983. */
  39984. height,
  39985. /**
  39986. * Defines the diameter of the cylinder's top cap
  39987. */
  39988. diameterTop,
  39989. /**
  39990. * Defines the diameter of the cylinder's bottom cap
  39991. */
  39992. diameterBottom,
  39993. /**
  39994. * Defines the tessellation factor to apply to the cylinder
  39995. */
  39996. tessellation,
  39997. /**
  39998. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39999. */
  40000. subdivisions, canBeRegenerated, mesh,
  40001. /**
  40002. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40003. */
  40004. side) {
  40005. if (subdivisions === void 0) { subdivisions = 1; }
  40006. if (mesh === void 0) { mesh = null; }
  40007. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40008. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40009. _this.height = height;
  40010. _this.diameterTop = diameterTop;
  40011. _this.diameterBottom = diameterBottom;
  40012. _this.tessellation = tessellation;
  40013. _this.subdivisions = subdivisions;
  40014. _this.side = side;
  40015. return _this;
  40016. }
  40017. CylinderGeometry.prototype._regenerateVertexData = function () {
  40018. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40019. };
  40020. CylinderGeometry.prototype.copy = function (id) {
  40021. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40022. };
  40023. CylinderGeometry.prototype.serialize = function () {
  40024. var serializationObject = _super.prototype.serialize.call(this);
  40025. serializationObject.height = this.height;
  40026. serializationObject.diameterTop = this.diameterTop;
  40027. serializationObject.diameterBottom = this.diameterBottom;
  40028. serializationObject.tessellation = this.tessellation;
  40029. return serializationObject;
  40030. };
  40031. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40032. if (scene.getGeometryByID(parsedCylinder.id)) {
  40033. return null; // null since geometry could be something else than a cylinder...
  40034. }
  40035. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40036. if (BABYLON.Tags) {
  40037. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40038. }
  40039. scene.pushGeometry(cylinder, true);
  40040. return cylinder;
  40041. };
  40042. return CylinderGeometry;
  40043. }(_PrimitiveGeometry));
  40044. BABYLON.CylinderGeometry = CylinderGeometry;
  40045. /**
  40046. * Creates a new torus geometry
  40047. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40048. */
  40049. var TorusGeometry = /** @class */ (function (_super) {
  40050. __extends(TorusGeometry, _super);
  40051. /**
  40052. * Creates a new torus geometry
  40053. * @param id defines the unique ID of the geometry
  40054. * @param scene defines the hosting scene
  40055. * @param diameter defines the diameter of the torus
  40056. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40057. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40058. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40059. * @param mesh defines the hosting mesh (can be null)
  40060. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40061. */
  40062. function TorusGeometry(id, scene,
  40063. /**
  40064. * Defines the diameter of the torus
  40065. */
  40066. diameter,
  40067. /**
  40068. * Defines the thickness of the torus (ie. internal diameter)
  40069. */
  40070. thickness,
  40071. /**
  40072. * Defines the tesselation factor to apply to the torus
  40073. */
  40074. tessellation, canBeRegenerated, mesh,
  40075. /**
  40076. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40077. */
  40078. side) {
  40079. if (mesh === void 0) { mesh = null; }
  40080. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40081. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40082. _this.diameter = diameter;
  40083. _this.thickness = thickness;
  40084. _this.tessellation = tessellation;
  40085. _this.side = side;
  40086. return _this;
  40087. }
  40088. TorusGeometry.prototype._regenerateVertexData = function () {
  40089. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40090. };
  40091. TorusGeometry.prototype.copy = function (id) {
  40092. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40093. };
  40094. TorusGeometry.prototype.serialize = function () {
  40095. var serializationObject = _super.prototype.serialize.call(this);
  40096. serializationObject.diameter = this.diameter;
  40097. serializationObject.thickness = this.thickness;
  40098. serializationObject.tessellation = this.tessellation;
  40099. return serializationObject;
  40100. };
  40101. TorusGeometry.Parse = function (parsedTorus, scene) {
  40102. if (scene.getGeometryByID(parsedTorus.id)) {
  40103. return null; // null since geometry could be something else than a torus...
  40104. }
  40105. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40106. if (BABYLON.Tags) {
  40107. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40108. }
  40109. scene.pushGeometry(torus, true);
  40110. return torus;
  40111. };
  40112. return TorusGeometry;
  40113. }(_PrimitiveGeometry));
  40114. BABYLON.TorusGeometry = TorusGeometry;
  40115. /**
  40116. * Creates a new ground geometry
  40117. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40118. */
  40119. var GroundGeometry = /** @class */ (function (_super) {
  40120. __extends(GroundGeometry, _super);
  40121. /**
  40122. * Creates a new ground geometry
  40123. * @param id defines the unique ID of the geometry
  40124. * @param scene defines the hosting scene
  40125. * @param width defines the width of the ground
  40126. * @param height defines the height of the ground
  40127. * @param subdivisions defines the subdivisions to apply to the ground
  40128. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40129. * @param mesh defines the hosting mesh (can be null)
  40130. */
  40131. function GroundGeometry(id, scene,
  40132. /**
  40133. * Defines the width of the ground
  40134. */
  40135. width,
  40136. /**
  40137. * Defines the height of the ground
  40138. */
  40139. height,
  40140. /**
  40141. * Defines the subdivisions to apply to the ground
  40142. */
  40143. subdivisions, canBeRegenerated, mesh) {
  40144. if (mesh === void 0) { mesh = null; }
  40145. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40146. _this.width = width;
  40147. _this.height = height;
  40148. _this.subdivisions = subdivisions;
  40149. return _this;
  40150. }
  40151. GroundGeometry.prototype._regenerateVertexData = function () {
  40152. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40153. };
  40154. GroundGeometry.prototype.copy = function (id) {
  40155. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40156. };
  40157. GroundGeometry.prototype.serialize = function () {
  40158. var serializationObject = _super.prototype.serialize.call(this);
  40159. serializationObject.width = this.width;
  40160. serializationObject.height = this.height;
  40161. serializationObject.subdivisions = this.subdivisions;
  40162. return serializationObject;
  40163. };
  40164. GroundGeometry.Parse = function (parsedGround, scene) {
  40165. if (scene.getGeometryByID(parsedGround.id)) {
  40166. return null; // null since geometry could be something else than a ground...
  40167. }
  40168. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40169. if (BABYLON.Tags) {
  40170. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40171. }
  40172. scene.pushGeometry(ground, true);
  40173. return ground;
  40174. };
  40175. return GroundGeometry;
  40176. }(_PrimitiveGeometry));
  40177. BABYLON.GroundGeometry = GroundGeometry;
  40178. /**
  40179. * Creates a tiled ground geometry
  40180. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40181. */
  40182. var TiledGroundGeometry = /** @class */ (function (_super) {
  40183. __extends(TiledGroundGeometry, _super);
  40184. /**
  40185. * Creates a tiled ground geometry
  40186. * @param id defines the unique ID of the geometry
  40187. * @param scene defines the hosting scene
  40188. * @param xmin defines the minimum value on X axis
  40189. * @param zmin defines the minimum value on Z axis
  40190. * @param xmax defines the maximum value on X axis
  40191. * @param zmax defines the maximum value on Z axis
  40192. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40193. * @param precision defines the precision to use when computing the tiles
  40194. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40195. * @param mesh defines the hosting mesh (can be null)
  40196. */
  40197. function TiledGroundGeometry(id, scene,
  40198. /**
  40199. * Defines the minimum value on X axis
  40200. */
  40201. xmin,
  40202. /**
  40203. * Defines the minimum value on Z axis
  40204. */
  40205. zmin,
  40206. /**
  40207. * Defines the maximum value on X axis
  40208. */
  40209. xmax,
  40210. /**
  40211. * Defines the maximum value on Z axis
  40212. */
  40213. zmax,
  40214. /**
  40215. * Defines the subdivisions to apply to the ground
  40216. */
  40217. subdivisions,
  40218. /**
  40219. * Defines the precision to use when computing the tiles
  40220. */
  40221. precision, canBeRegenerated, mesh) {
  40222. if (mesh === void 0) { mesh = null; }
  40223. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40224. _this.xmin = xmin;
  40225. _this.zmin = zmin;
  40226. _this.xmax = xmax;
  40227. _this.zmax = zmax;
  40228. _this.subdivisions = subdivisions;
  40229. _this.precision = precision;
  40230. return _this;
  40231. }
  40232. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40233. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40234. };
  40235. TiledGroundGeometry.prototype.copy = function (id) {
  40236. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40237. };
  40238. return TiledGroundGeometry;
  40239. }(_PrimitiveGeometry));
  40240. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40241. /**
  40242. * Creates a plane geometry
  40243. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40244. */
  40245. var PlaneGeometry = /** @class */ (function (_super) {
  40246. __extends(PlaneGeometry, _super);
  40247. /**
  40248. * Creates a plane geometry
  40249. * @param id defines the unique ID of the geometry
  40250. * @param scene defines the hosting scene
  40251. * @param size defines the size of the plane (width === height)
  40252. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40253. * @param mesh defines the hosting mesh (can be null)
  40254. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40255. */
  40256. function PlaneGeometry(id, scene,
  40257. /**
  40258. * Defines the size of the plane (width === height)
  40259. */
  40260. size, canBeRegenerated, mesh,
  40261. /**
  40262. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. side) {
  40265. if (mesh === void 0) { mesh = null; }
  40266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40267. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40268. _this.size = size;
  40269. _this.side = side;
  40270. return _this;
  40271. }
  40272. PlaneGeometry.prototype._regenerateVertexData = function () {
  40273. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40274. };
  40275. PlaneGeometry.prototype.copy = function (id) {
  40276. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40277. };
  40278. PlaneGeometry.prototype.serialize = function () {
  40279. var serializationObject = _super.prototype.serialize.call(this);
  40280. serializationObject.size = this.size;
  40281. return serializationObject;
  40282. };
  40283. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40284. if (scene.getGeometryByID(parsedPlane.id)) {
  40285. return null; // null since geometry could be something else than a ground...
  40286. }
  40287. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40288. if (BABYLON.Tags) {
  40289. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40290. }
  40291. scene.pushGeometry(plane, true);
  40292. return plane;
  40293. };
  40294. return PlaneGeometry;
  40295. }(_PrimitiveGeometry));
  40296. BABYLON.PlaneGeometry = PlaneGeometry;
  40297. /**
  40298. * Creates a torus knot geometry
  40299. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40300. */
  40301. var TorusKnotGeometry = /** @class */ (function (_super) {
  40302. __extends(TorusKnotGeometry, _super);
  40303. /**
  40304. * Creates a torus knot geometry
  40305. * @param id defines the unique ID of the geometry
  40306. * @param scene defines the hosting scene
  40307. * @param radius defines the radius of the torus knot
  40308. * @param tube defines the thickness of the torus knot tube
  40309. * @param radialSegments defines the number of radial segments
  40310. * @param tubularSegments defines the number of tubular segments
  40311. * @param p defines the first number of windings
  40312. * @param q defines the second number of windings
  40313. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40314. * @param mesh defines the hosting mesh (can be null)
  40315. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40316. */
  40317. function TorusKnotGeometry(id, scene,
  40318. /**
  40319. * Defines the radius of the torus knot
  40320. */
  40321. radius,
  40322. /**
  40323. * Defines the thickness of the torus knot tube
  40324. */
  40325. tube,
  40326. /**
  40327. * Defines the number of radial segments
  40328. */
  40329. radialSegments,
  40330. /**
  40331. * Defines the number of tubular segments
  40332. */
  40333. tubularSegments,
  40334. /**
  40335. * Defines the first number of windings
  40336. */
  40337. p,
  40338. /**
  40339. * Defines the second number of windings
  40340. */
  40341. q, canBeRegenerated, mesh,
  40342. /**
  40343. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40344. */
  40345. side) {
  40346. if (mesh === void 0) { mesh = null; }
  40347. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40348. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40349. _this.radius = radius;
  40350. _this.tube = tube;
  40351. _this.radialSegments = radialSegments;
  40352. _this.tubularSegments = tubularSegments;
  40353. _this.p = p;
  40354. _this.q = q;
  40355. _this.side = side;
  40356. return _this;
  40357. }
  40358. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40359. 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 });
  40360. };
  40361. TorusKnotGeometry.prototype.copy = function (id) {
  40362. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40363. };
  40364. TorusKnotGeometry.prototype.serialize = function () {
  40365. var serializationObject = _super.prototype.serialize.call(this);
  40366. serializationObject.radius = this.radius;
  40367. serializationObject.tube = this.tube;
  40368. serializationObject.radialSegments = this.radialSegments;
  40369. serializationObject.tubularSegments = this.tubularSegments;
  40370. serializationObject.p = this.p;
  40371. serializationObject.q = this.q;
  40372. return serializationObject;
  40373. };
  40374. ;
  40375. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40376. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40377. return null; // null since geometry could be something else than a ground...
  40378. }
  40379. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40380. if (BABYLON.Tags) {
  40381. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40382. }
  40383. scene.pushGeometry(torusKnot, true);
  40384. return torusKnot;
  40385. };
  40386. return TorusKnotGeometry;
  40387. }(_PrimitiveGeometry));
  40388. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40389. //}
  40390. })(BABYLON || (BABYLON = {}));
  40391. //# sourceMappingURL=babylon.geometry.js.map
  40392. var BABYLON;
  40393. (function (BABYLON) {
  40394. /**
  40395. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40396. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40397. */
  40398. var PostProcessManager = /** @class */ (function () {
  40399. /**
  40400. * Creates a new instance PostProcess
  40401. * @param scene The scene that the post process is associated with.
  40402. */
  40403. function PostProcessManager(scene) {
  40404. this._vertexBuffers = {};
  40405. this._scene = scene;
  40406. }
  40407. PostProcessManager.prototype._prepareBuffers = function () {
  40408. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40409. return;
  40410. }
  40411. // VBO
  40412. var vertices = [];
  40413. vertices.push(1, 1);
  40414. vertices.push(-1, 1);
  40415. vertices.push(-1, -1);
  40416. vertices.push(1, -1);
  40417. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40418. this._buildIndexBuffer();
  40419. };
  40420. PostProcessManager.prototype._buildIndexBuffer = function () {
  40421. // Indices
  40422. var indices = [];
  40423. indices.push(0);
  40424. indices.push(1);
  40425. indices.push(2);
  40426. indices.push(0);
  40427. indices.push(2);
  40428. indices.push(3);
  40429. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40430. };
  40431. /**
  40432. * Rebuilds the vertex buffers of the manager.
  40433. */
  40434. PostProcessManager.prototype._rebuild = function () {
  40435. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40436. if (!vb) {
  40437. return;
  40438. }
  40439. vb._rebuild();
  40440. this._buildIndexBuffer();
  40441. };
  40442. // Methods
  40443. /**
  40444. * Prepares a frame to be run through a post process.
  40445. * @param sourceTexture The input texture to the post procesess. (default: null)
  40446. * @param postProcesses An array of post processes to be run. (default: null)
  40447. * @returns True if the post processes were able to be run.
  40448. */
  40449. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40450. if (sourceTexture === void 0) { sourceTexture = null; }
  40451. if (postProcesses === void 0) { postProcesses = null; }
  40452. var camera = this._scene.activeCamera;
  40453. if (!camera) {
  40454. return false;
  40455. }
  40456. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40457. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40458. return false;
  40459. }
  40460. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40461. return true;
  40462. };
  40463. /**
  40464. * Manually render a set of post processes to a texture.
  40465. * @param postProcesses An array of post processes to be run.
  40466. * @param targetTexture The target texture to render to.
  40467. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40468. */
  40469. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40470. if (targetTexture === void 0) { targetTexture = null; }
  40471. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40472. var engine = this._scene.getEngine();
  40473. for (var index = 0; index < postProcesses.length; index++) {
  40474. if (index < postProcesses.length - 1) {
  40475. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40476. }
  40477. else {
  40478. if (targetTexture) {
  40479. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40480. }
  40481. else {
  40482. engine.restoreDefaultFramebuffer();
  40483. }
  40484. }
  40485. var pp = postProcesses[index];
  40486. var effect = pp.apply();
  40487. if (effect) {
  40488. pp.onBeforeRenderObservable.notifyObservers(effect);
  40489. // VBOs
  40490. this._prepareBuffers();
  40491. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40492. // Draw order
  40493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40494. pp.onAfterRenderObservable.notifyObservers(effect);
  40495. }
  40496. }
  40497. // Restore depth buffer
  40498. engine.setDepthBuffer(true);
  40499. engine.setDepthWrite(true);
  40500. };
  40501. /**
  40502. * Finalize the result of the output of the postprocesses.
  40503. * @param doNotPresent If true the result will not be displayed to the screen.
  40504. * @param targetTexture The target texture to render to.
  40505. * @param faceIndex The index of the face to bind the target texture to.
  40506. * @param postProcesses The array of post processes to render.
  40507. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40508. */
  40509. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40510. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40511. var camera = this._scene.activeCamera;
  40512. if (!camera) {
  40513. return;
  40514. }
  40515. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40516. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40517. return;
  40518. }
  40519. var engine = this._scene.getEngine();
  40520. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40521. var pp = postProcesses[index];
  40522. if (index < len - 1) {
  40523. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40524. }
  40525. else {
  40526. if (targetTexture) {
  40527. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40528. pp._outputTexture = targetTexture;
  40529. }
  40530. else {
  40531. engine.restoreDefaultFramebuffer();
  40532. pp._outputTexture = null;
  40533. }
  40534. }
  40535. if (doNotPresent) {
  40536. break;
  40537. }
  40538. var effect = pp.apply();
  40539. if (effect) {
  40540. pp.onBeforeRenderObservable.notifyObservers(effect);
  40541. // VBOs
  40542. this._prepareBuffers();
  40543. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40544. // Draw order
  40545. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40546. pp.onAfterRenderObservable.notifyObservers(effect);
  40547. }
  40548. }
  40549. // Restore states
  40550. engine.setDepthBuffer(true);
  40551. engine.setDepthWrite(true);
  40552. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40553. };
  40554. /**
  40555. * Disposes of the post process manager.
  40556. */
  40557. PostProcessManager.prototype.dispose = function () {
  40558. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40559. if (buffer) {
  40560. buffer.dispose();
  40561. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40562. }
  40563. if (this._indexBuffer) {
  40564. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40565. this._indexBuffer = null;
  40566. }
  40567. };
  40568. return PostProcessManager;
  40569. }());
  40570. BABYLON.PostProcessManager = PostProcessManager;
  40571. })(BABYLON || (BABYLON = {}));
  40572. //# sourceMappingURL=babylon.postProcessManager.js.map
  40573. var BABYLON;
  40574. (function (BABYLON) {
  40575. /**
  40576. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40577. */
  40578. var PerformanceMonitor = /** @class */ (function () {
  40579. /**
  40580. * constructor
  40581. * @param frameSampleSize The number of samples required to saturate the sliding window
  40582. */
  40583. function PerformanceMonitor(frameSampleSize) {
  40584. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40585. this._enabled = true;
  40586. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40587. }
  40588. /**
  40589. * Samples current frame
  40590. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40591. */
  40592. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40593. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40594. if (!this._enabled)
  40595. return;
  40596. if (this._lastFrameTimeMs != null) {
  40597. var dt = timeMs - this._lastFrameTimeMs;
  40598. this._rollingFrameTime.add(dt);
  40599. }
  40600. this._lastFrameTimeMs = timeMs;
  40601. };
  40602. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40603. /**
  40604. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40605. * @return Average frame time in milliseconds
  40606. */
  40607. get: function () {
  40608. return this._rollingFrameTime.average;
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40614. /**
  40615. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40616. * @return Frame time variance in milliseconds squared
  40617. */
  40618. get: function () {
  40619. return this._rollingFrameTime.variance;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40625. /**
  40626. * Returns the frame time of the most recent frame
  40627. * @return Frame time in milliseconds
  40628. */
  40629. get: function () {
  40630. return this._rollingFrameTime.history(0);
  40631. },
  40632. enumerable: true,
  40633. configurable: true
  40634. });
  40635. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40636. /**
  40637. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40638. * @return Framerate in frames per second
  40639. */
  40640. get: function () {
  40641. return 1000.0 / this._rollingFrameTime.average;
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40647. /**
  40648. * Returns the average framerate in frames per second using the most recent frame time
  40649. * @return Framerate in frames per second
  40650. */
  40651. get: function () {
  40652. var history = this._rollingFrameTime.history(0);
  40653. if (history === 0) {
  40654. return 0;
  40655. }
  40656. return 1000.0 / history;
  40657. },
  40658. enumerable: true,
  40659. configurable: true
  40660. });
  40661. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40662. /**
  40663. * Returns true if enough samples have been taken to completely fill the sliding window
  40664. * @return true if saturated
  40665. */
  40666. get: function () {
  40667. return this._rollingFrameTime.isSaturated();
  40668. },
  40669. enumerable: true,
  40670. configurable: true
  40671. });
  40672. /**
  40673. * Enables contributions to the sliding window sample set
  40674. */
  40675. PerformanceMonitor.prototype.enable = function () {
  40676. this._enabled = true;
  40677. };
  40678. /**
  40679. * Disables contributions to the sliding window sample set
  40680. * Samples will not be interpolated over the disabled period
  40681. */
  40682. PerformanceMonitor.prototype.disable = function () {
  40683. this._enabled = false;
  40684. //clear last sample to avoid interpolating over the disabled period when next enabled
  40685. this._lastFrameTimeMs = null;
  40686. };
  40687. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40688. /**
  40689. * Returns true if sampling is enabled
  40690. * @return true if enabled
  40691. */
  40692. get: function () {
  40693. return this._enabled;
  40694. },
  40695. enumerable: true,
  40696. configurable: true
  40697. });
  40698. /**
  40699. * Resets performance monitor
  40700. */
  40701. PerformanceMonitor.prototype.reset = function () {
  40702. //clear last sample to avoid interpolating over the disabled period when next enabled
  40703. this._lastFrameTimeMs = null;
  40704. //wipe record
  40705. this._rollingFrameTime.reset();
  40706. };
  40707. return PerformanceMonitor;
  40708. }());
  40709. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40710. /**
  40711. * RollingAverage
  40712. *
  40713. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40714. */
  40715. var RollingAverage = /** @class */ (function () {
  40716. /**
  40717. * constructor
  40718. * @param length The number of samples required to saturate the sliding window
  40719. */
  40720. function RollingAverage(length) {
  40721. this._samples = new Array(length);
  40722. this.reset();
  40723. }
  40724. /**
  40725. * Adds a sample to the sample set
  40726. * @param v The sample value
  40727. */
  40728. RollingAverage.prototype.add = function (v) {
  40729. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40730. var delta;
  40731. //we need to check if we've already wrapped round
  40732. if (this.isSaturated()) {
  40733. //remove bottom of stack from mean
  40734. var bottomValue = this._samples[this._pos];
  40735. delta = bottomValue - this.average;
  40736. this.average -= delta / (this._sampleCount - 1);
  40737. this._m2 -= delta * (bottomValue - this.average);
  40738. }
  40739. else {
  40740. this._sampleCount++;
  40741. }
  40742. //add new value to mean
  40743. delta = v - this.average;
  40744. this.average += delta / (this._sampleCount);
  40745. this._m2 += delta * (v - this.average);
  40746. //set the new variance
  40747. this.variance = this._m2 / (this._sampleCount - 1);
  40748. this._samples[this._pos] = v;
  40749. this._pos++;
  40750. this._pos %= this._samples.length; //positive wrap around
  40751. };
  40752. /**
  40753. * Returns previously added values or null if outside of history or outside the sliding window domain
  40754. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40755. * @return Value previously recorded with add() or null if outside of range
  40756. */
  40757. RollingAverage.prototype.history = function (i) {
  40758. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40759. return 0;
  40760. }
  40761. var i0 = this._wrapPosition(this._pos - 1.0);
  40762. return this._samples[this._wrapPosition(i0 - i)];
  40763. };
  40764. /**
  40765. * Returns true if enough samples have been taken to completely fill the sliding window
  40766. * @return true if sample-set saturated
  40767. */
  40768. RollingAverage.prototype.isSaturated = function () {
  40769. return this._sampleCount >= this._samples.length;
  40770. };
  40771. /**
  40772. * Resets the rolling average (equivalent to 0 samples taken so far)
  40773. */
  40774. RollingAverage.prototype.reset = function () {
  40775. this.average = 0;
  40776. this.variance = 0;
  40777. this._sampleCount = 0;
  40778. this._pos = 0;
  40779. this._m2 = 0;
  40780. };
  40781. /**
  40782. * Wraps a value around the sample range boundaries
  40783. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40784. * @return Wrapped position in sample range
  40785. */
  40786. RollingAverage.prototype._wrapPosition = function (i) {
  40787. var max = this._samples.length;
  40788. return ((i % max) + max) % max;
  40789. };
  40790. return RollingAverage;
  40791. }());
  40792. BABYLON.RollingAverage = RollingAverage;
  40793. })(BABYLON || (BABYLON = {}));
  40794. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40795. var BABYLON;
  40796. (function (BABYLON) {
  40797. /**
  40798. * This groups together the common properties used for image processing either in direct forward pass
  40799. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40800. * or not.
  40801. */
  40802. var ImageProcessingConfiguration = /** @class */ (function () {
  40803. function ImageProcessingConfiguration() {
  40804. /**
  40805. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40806. */
  40807. this.colorCurves = new BABYLON.ColorCurves();
  40808. this._colorCurvesEnabled = false;
  40809. this._colorGradingEnabled = false;
  40810. this._colorGradingWithGreenDepth = true;
  40811. this._colorGradingBGR = true;
  40812. this._exposure = 1.0;
  40813. this._toneMappingEnabled = false;
  40814. this._contrast = 1.0;
  40815. /**
  40816. * Vignette stretch size.
  40817. */
  40818. this.vignetteStretch = 0;
  40819. /**
  40820. * Vignette centre X Offset.
  40821. */
  40822. this.vignetteCentreX = 0;
  40823. /**
  40824. * Vignette centre Y Offset.
  40825. */
  40826. this.vignetteCentreY = 0;
  40827. /**
  40828. * Vignette weight or intensity of the vignette effect.
  40829. */
  40830. this.vignetteWeight = 1.5;
  40831. /**
  40832. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40833. * if vignetteEnabled is set to true.
  40834. */
  40835. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40836. /**
  40837. * Camera field of view used by the Vignette effect.
  40838. */
  40839. this.vignetteCameraFov = 0.5;
  40840. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40841. this._vignetteEnabled = false;
  40842. this._applyByPostProcess = false;
  40843. this._isEnabled = true;
  40844. /**
  40845. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40846. */
  40847. this.onUpdateParameters = new BABYLON.Observable();
  40848. }
  40849. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40850. /**
  40851. * Gets wether the color curves effect is enabled.
  40852. */
  40853. get: function () {
  40854. return this._colorCurvesEnabled;
  40855. },
  40856. /**
  40857. * Sets wether the color curves effect is enabled.
  40858. */
  40859. set: function (value) {
  40860. if (this._colorCurvesEnabled === value) {
  40861. return;
  40862. }
  40863. this._colorCurvesEnabled = value;
  40864. this._updateParameters();
  40865. },
  40866. enumerable: true,
  40867. configurable: true
  40868. });
  40869. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40870. /**
  40871. * Gets wether the color grading effect is enabled.
  40872. */
  40873. get: function () {
  40874. return this._colorGradingEnabled;
  40875. },
  40876. /**
  40877. * Sets wether the color grading effect is enabled.
  40878. */
  40879. set: function (value) {
  40880. if (this._colorGradingEnabled === value) {
  40881. return;
  40882. }
  40883. this._colorGradingEnabled = value;
  40884. this._updateParameters();
  40885. },
  40886. enumerable: true,
  40887. configurable: true
  40888. });
  40889. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40890. /**
  40891. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40892. */
  40893. get: function () {
  40894. return this._colorGradingWithGreenDepth;
  40895. },
  40896. /**
  40897. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40898. */
  40899. set: function (value) {
  40900. if (this._colorGradingWithGreenDepth === value) {
  40901. return;
  40902. }
  40903. this._colorGradingWithGreenDepth = value;
  40904. this._updateParameters();
  40905. },
  40906. enumerable: true,
  40907. configurable: true
  40908. });
  40909. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40910. /**
  40911. * Gets wether the color grading texture contains BGR values.
  40912. */
  40913. get: function () {
  40914. return this._colorGradingBGR;
  40915. },
  40916. /**
  40917. * Sets wether the color grading texture contains BGR values.
  40918. */
  40919. set: function (value) {
  40920. if (this._colorGradingBGR === value) {
  40921. return;
  40922. }
  40923. this._colorGradingBGR = value;
  40924. this._updateParameters();
  40925. },
  40926. enumerable: true,
  40927. configurable: true
  40928. });
  40929. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40930. /**
  40931. * Gets the Exposure used in the effect.
  40932. */
  40933. get: function () {
  40934. return this._exposure;
  40935. },
  40936. /**
  40937. * Sets the Exposure used in the effect.
  40938. */
  40939. set: function (value) {
  40940. if (this._exposure === value) {
  40941. return;
  40942. }
  40943. this._exposure = value;
  40944. this._updateParameters();
  40945. },
  40946. enumerable: true,
  40947. configurable: true
  40948. });
  40949. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40950. /**
  40951. * Gets wether the tone mapping effect is enabled.
  40952. */
  40953. get: function () {
  40954. return this._toneMappingEnabled;
  40955. },
  40956. /**
  40957. * Sets wether the tone mapping effect is enabled.
  40958. */
  40959. set: function (value) {
  40960. if (this._toneMappingEnabled === value) {
  40961. return;
  40962. }
  40963. this._toneMappingEnabled = value;
  40964. this._updateParameters();
  40965. },
  40966. enumerable: true,
  40967. configurable: true
  40968. });
  40969. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40970. /**
  40971. * Gets the contrast used in the effect.
  40972. */
  40973. get: function () {
  40974. return this._contrast;
  40975. },
  40976. /**
  40977. * Sets the contrast used in the effect.
  40978. */
  40979. set: function (value) {
  40980. if (this._contrast === value) {
  40981. return;
  40982. }
  40983. this._contrast = value;
  40984. this._updateParameters();
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40990. /**
  40991. * Gets the vignette blend mode allowing different kind of effect.
  40992. */
  40993. get: function () {
  40994. return this._vignetteBlendMode;
  40995. },
  40996. /**
  40997. * Sets the vignette blend mode allowing different kind of effect.
  40998. */
  40999. set: function (value) {
  41000. if (this._vignetteBlendMode === value) {
  41001. return;
  41002. }
  41003. this._vignetteBlendMode = value;
  41004. this._updateParameters();
  41005. },
  41006. enumerable: true,
  41007. configurable: true
  41008. });
  41009. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41010. /**
  41011. * Gets wether the vignette effect is enabled.
  41012. */
  41013. get: function () {
  41014. return this._vignetteEnabled;
  41015. },
  41016. /**
  41017. * Sets wether the vignette effect is enabled.
  41018. */
  41019. set: function (value) {
  41020. if (this._vignetteEnabled === value) {
  41021. return;
  41022. }
  41023. this._vignetteEnabled = value;
  41024. this._updateParameters();
  41025. },
  41026. enumerable: true,
  41027. configurable: true
  41028. });
  41029. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41030. /**
  41031. * Gets wether the image processing is applied through a post process or not.
  41032. */
  41033. get: function () {
  41034. return this._applyByPostProcess;
  41035. },
  41036. /**
  41037. * Sets wether the image processing is applied through a post process or not.
  41038. */
  41039. set: function (value) {
  41040. if (this._applyByPostProcess === value) {
  41041. return;
  41042. }
  41043. this._applyByPostProcess = value;
  41044. this._updateParameters();
  41045. },
  41046. enumerable: true,
  41047. configurable: true
  41048. });
  41049. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41050. /**
  41051. * Gets wether the image processing is enabled or not.
  41052. */
  41053. get: function () {
  41054. return this._isEnabled;
  41055. },
  41056. /**
  41057. * Sets wether the image processing is enabled or not.
  41058. */
  41059. set: function (value) {
  41060. if (this._isEnabled === value) {
  41061. return;
  41062. }
  41063. this._isEnabled = value;
  41064. this._updateParameters();
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. /**
  41070. * Method called each time the image processing information changes requires to recompile the effect.
  41071. */
  41072. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41073. this.onUpdateParameters.notifyObservers(this);
  41074. };
  41075. ImageProcessingConfiguration.prototype.getClassName = function () {
  41076. return "ImageProcessingConfiguration";
  41077. };
  41078. /**
  41079. * Prepare the list of uniforms associated with the Image Processing effects.
  41080. * @param uniformsList The list of uniforms used in the effect
  41081. * @param defines the list of defines currently in use
  41082. */
  41083. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41084. if (defines.EXPOSURE) {
  41085. uniforms.push("exposureLinear");
  41086. }
  41087. if (defines.CONTRAST) {
  41088. uniforms.push("contrast");
  41089. }
  41090. if (defines.COLORGRADING) {
  41091. uniforms.push("colorTransformSettings");
  41092. }
  41093. if (defines.VIGNETTE) {
  41094. uniforms.push("vInverseScreenSize");
  41095. uniforms.push("vignetteSettings1");
  41096. uniforms.push("vignetteSettings2");
  41097. }
  41098. if (defines.COLORCURVES) {
  41099. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41100. }
  41101. };
  41102. /**
  41103. * Prepare the list of samplers associated with the Image Processing effects.
  41104. * @param uniformsList The list of uniforms used in the effect
  41105. * @param defines the list of defines currently in use
  41106. */
  41107. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41108. if (defines.COLORGRADING) {
  41109. samplersList.push("txColorTransform");
  41110. }
  41111. };
  41112. /**
  41113. * Prepare the list of defines associated to the shader.
  41114. * @param defines the list of defines to complete
  41115. */
  41116. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41117. if (forPostProcess === void 0) { forPostProcess = false; }
  41118. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41119. defines.VIGNETTE = false;
  41120. defines.TONEMAPPING = false;
  41121. defines.CONTRAST = false;
  41122. defines.EXPOSURE = false;
  41123. defines.COLORCURVES = false;
  41124. defines.COLORGRADING = false;
  41125. defines.COLORGRADING3D = false;
  41126. defines.IMAGEPROCESSING = false;
  41127. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41128. return;
  41129. }
  41130. defines.VIGNETTE = this.vignetteEnabled;
  41131. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41132. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41133. defines.TONEMAPPING = this.toneMappingEnabled;
  41134. defines.CONTRAST = (this.contrast !== 1.0);
  41135. defines.EXPOSURE = (this.exposure !== 1.0);
  41136. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41137. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41138. if (defines.COLORGRADING) {
  41139. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41140. }
  41141. else {
  41142. defines.COLORGRADING3D = false;
  41143. }
  41144. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41145. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41146. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41147. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41148. };
  41149. /**
  41150. * Returns true if all the image processing information are ready.
  41151. */
  41152. ImageProcessingConfiguration.prototype.isReady = function () {
  41153. // Color Grading texure can not be none blocking.
  41154. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41155. };
  41156. /**
  41157. * Binds the image processing to the shader.
  41158. * @param effect The effect to bind to
  41159. */
  41160. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41161. if (aspectRatio === void 0) { aspectRatio = 1; }
  41162. // Color Curves
  41163. if (this._colorCurvesEnabled && this.colorCurves) {
  41164. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41165. }
  41166. // Vignette
  41167. if (this._vignetteEnabled) {
  41168. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41169. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41170. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41171. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41172. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41173. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41174. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41175. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41176. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41177. var vignettePower = -2.0 * this.vignetteWeight;
  41178. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41179. }
  41180. // Exposure
  41181. effect.setFloat("exposureLinear", this.exposure);
  41182. // Contrast
  41183. effect.setFloat("contrast", this.contrast);
  41184. // Color transform settings
  41185. if (this.colorGradingTexture) {
  41186. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41187. var textureSize = this.colorGradingTexture.getSize().height;
  41188. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41189. 0.5 / textureSize, // textureOffset
  41190. textureSize, // textureSize
  41191. this.colorGradingTexture.level // weight
  41192. );
  41193. }
  41194. };
  41195. /**
  41196. * Clones the current image processing instance.
  41197. * @return The cloned image processing
  41198. */
  41199. ImageProcessingConfiguration.prototype.clone = function () {
  41200. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41201. };
  41202. /**
  41203. * Serializes the current image processing instance to a json representation.
  41204. * @return a JSON representation
  41205. */
  41206. ImageProcessingConfiguration.prototype.serialize = function () {
  41207. return BABYLON.SerializationHelper.Serialize(this);
  41208. };
  41209. /**
  41210. * Parses the image processing from a json representation.
  41211. * @param source the JSON source to parse
  41212. * @return The parsed image processing
  41213. */
  41214. ImageProcessingConfiguration.Parse = function (source) {
  41215. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41216. };
  41217. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41218. /**
  41219. * Used to apply the vignette as a mix with the pixel color.
  41220. */
  41221. get: function () {
  41222. return this._VIGNETTEMODE_MULTIPLY;
  41223. },
  41224. enumerable: true,
  41225. configurable: true
  41226. });
  41227. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41228. /**
  41229. * Used to apply the vignette as a replacement of the pixel color.
  41230. */
  41231. get: function () {
  41232. return this._VIGNETTEMODE_OPAQUE;
  41233. },
  41234. enumerable: true,
  41235. configurable: true
  41236. });
  41237. // Static constants associated to the image processing.
  41238. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41239. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41240. __decorate([
  41241. BABYLON.serializeAsColorCurves()
  41242. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41243. __decorate([
  41244. BABYLON.serialize()
  41245. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41246. __decorate([
  41247. BABYLON.serializeAsTexture()
  41248. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41249. __decorate([
  41250. BABYLON.serialize()
  41251. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41252. __decorate([
  41253. BABYLON.serialize()
  41254. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41255. __decorate([
  41256. BABYLON.serialize()
  41257. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41258. __decorate([
  41259. BABYLON.serialize()
  41260. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41261. __decorate([
  41262. BABYLON.serialize()
  41263. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41264. __decorate([
  41265. BABYLON.serialize()
  41266. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41267. __decorate([
  41268. BABYLON.serialize()
  41269. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41270. __decorate([
  41271. BABYLON.serialize()
  41272. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41273. __decorate([
  41274. BABYLON.serialize()
  41275. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41276. __decorate([
  41277. BABYLON.serialize()
  41278. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41279. __decorate([
  41280. BABYLON.serializeAsColor4()
  41281. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41282. __decorate([
  41283. BABYLON.serialize()
  41284. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41285. __decorate([
  41286. BABYLON.serialize()
  41287. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41288. __decorate([
  41289. BABYLON.serialize()
  41290. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41291. __decorate([
  41292. BABYLON.serialize()
  41293. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41294. __decorate([
  41295. BABYLON.serialize()
  41296. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41297. return ImageProcessingConfiguration;
  41298. }());
  41299. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41300. })(BABYLON || (BABYLON = {}));
  41301. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41302. var BABYLON;
  41303. (function (BABYLON) {
  41304. /**
  41305. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41306. * It can help converting any input color in a desired output one. This can then be used to create effects
  41307. * from sepia, black and white to sixties or futuristic rendering...
  41308. *
  41309. * The only supported format is currently 3dl.
  41310. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41311. */
  41312. var ColorGradingTexture = /** @class */ (function (_super) {
  41313. __extends(ColorGradingTexture, _super);
  41314. /**
  41315. * Instantiates a ColorGradingTexture from the following parameters.
  41316. *
  41317. * @param url The location of the color gradind data (currently only supporting 3dl)
  41318. * @param scene The scene the texture will be used in
  41319. */
  41320. function ColorGradingTexture(url, scene) {
  41321. var _this = _super.call(this, scene) || this;
  41322. if (!url) {
  41323. return _this;
  41324. }
  41325. _this._engine = scene.getEngine();
  41326. _this._textureMatrix = BABYLON.Matrix.Identity();
  41327. _this.name = url;
  41328. _this.url = url;
  41329. _this.hasAlpha = false;
  41330. _this.isCube = false;
  41331. _this.is3D = _this._engine.webGLVersion > 1;
  41332. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41333. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41334. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41335. _this.anisotropicFilteringLevel = 1;
  41336. _this._texture = _this._getFromCache(url, true);
  41337. if (!_this._texture) {
  41338. if (!scene.useDelayedTextureLoading) {
  41339. _this.loadTexture();
  41340. }
  41341. else {
  41342. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41343. }
  41344. }
  41345. return _this;
  41346. }
  41347. /**
  41348. * Returns the texture matrix used in most of the material.
  41349. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41350. */
  41351. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41352. return this._textureMatrix;
  41353. };
  41354. /**
  41355. * Occurs when the file being loaded is a .3dl LUT file.
  41356. */
  41357. ColorGradingTexture.prototype.load3dlTexture = function () {
  41358. var engine = this._engine;
  41359. var texture;
  41360. if (engine.webGLVersion === 1) {
  41361. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41362. }
  41363. else {
  41364. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41365. }
  41366. this._texture = texture;
  41367. var callback = function (text) {
  41368. if (typeof text !== "string") {
  41369. return;
  41370. }
  41371. var data = null;
  41372. var tempData = null;
  41373. var line;
  41374. var lines = text.split('\n');
  41375. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41376. var maxColor = 0;
  41377. for (var i = 0; i < lines.length; i++) {
  41378. line = lines[i];
  41379. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41380. continue;
  41381. if (line.indexOf('#') === 0)
  41382. continue;
  41383. var words = line.split(" ");
  41384. if (size === 0) {
  41385. // Number of space + one
  41386. size = words.length;
  41387. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41388. tempData = new Float32Array(size * size * size * 4);
  41389. continue;
  41390. }
  41391. if (size != 0) {
  41392. var r = Math.max(parseInt(words[0]), 0);
  41393. var g = Math.max(parseInt(words[1]), 0);
  41394. var b = Math.max(parseInt(words[2]), 0);
  41395. maxColor = Math.max(r, maxColor);
  41396. maxColor = Math.max(g, maxColor);
  41397. maxColor = Math.max(b, maxColor);
  41398. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41399. if (tempData) {
  41400. tempData[pixelStorageIndex + 0] = r;
  41401. tempData[pixelStorageIndex + 1] = g;
  41402. tempData[pixelStorageIndex + 2] = b;
  41403. }
  41404. pixelIndexSlice++;
  41405. if (pixelIndexSlice % size == 0) {
  41406. pixelIndexH++;
  41407. pixelIndexSlice = 0;
  41408. if (pixelIndexH % size == 0) {
  41409. pixelIndexW++;
  41410. pixelIndexH = 0;
  41411. }
  41412. }
  41413. }
  41414. }
  41415. if (tempData && data) {
  41416. for (var i = 0; i < tempData.length; i++) {
  41417. if (i > 0 && (i + 1) % 4 === 0) {
  41418. data[i] = 255;
  41419. }
  41420. else {
  41421. var value = tempData[i];
  41422. data[i] = (value / maxColor * 255);
  41423. }
  41424. }
  41425. }
  41426. if (texture.is3D) {
  41427. texture.updateSize(size, size, size);
  41428. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41429. }
  41430. else {
  41431. texture.updateSize(size * size, size);
  41432. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41433. }
  41434. };
  41435. var scene = this.getScene();
  41436. if (scene) {
  41437. scene._loadFile(this.url, callback);
  41438. }
  41439. else {
  41440. this._engine._loadFile(this.url, callback);
  41441. }
  41442. return this._texture;
  41443. };
  41444. /**
  41445. * Starts the loading process of the texture.
  41446. */
  41447. ColorGradingTexture.prototype.loadTexture = function () {
  41448. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41449. this.load3dlTexture();
  41450. }
  41451. };
  41452. /**
  41453. * Clones the color gradind texture.
  41454. */
  41455. ColorGradingTexture.prototype.clone = function () {
  41456. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41457. // Base texture
  41458. newTexture.level = this.level;
  41459. return newTexture;
  41460. };
  41461. /**
  41462. * Called during delayed load for textures.
  41463. */
  41464. ColorGradingTexture.prototype.delayLoad = function () {
  41465. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41466. return;
  41467. }
  41468. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41469. this._texture = this._getFromCache(this.url, true);
  41470. if (!this._texture) {
  41471. this.loadTexture();
  41472. }
  41473. };
  41474. /**
  41475. * Parses a color grading texture serialized by Babylon.
  41476. * @param parsedTexture The texture information being parsedTexture
  41477. * @param scene The scene to load the texture in
  41478. * @param rootUrl The root url of the data assets to load
  41479. * @return A color gradind texture
  41480. */
  41481. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41482. var texture = null;
  41483. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41484. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41485. texture.name = parsedTexture.name;
  41486. texture.level = parsedTexture.level;
  41487. }
  41488. return texture;
  41489. };
  41490. /**
  41491. * Serializes the LUT texture to json format.
  41492. */
  41493. ColorGradingTexture.prototype.serialize = function () {
  41494. if (!this.name) {
  41495. return null;
  41496. }
  41497. var serializationObject = {};
  41498. serializationObject.name = this.name;
  41499. serializationObject.level = this.level;
  41500. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41501. return serializationObject;
  41502. };
  41503. /**
  41504. * Empty line regex stored for GC.
  41505. */
  41506. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41507. return ColorGradingTexture;
  41508. }(BABYLON.BaseTexture));
  41509. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41510. })(BABYLON || (BABYLON = {}));
  41511. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41512. var BABYLON;
  41513. (function (BABYLON) {
  41514. /**
  41515. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41516. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41517. * 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;
  41518. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41519. */
  41520. var ColorCurves = /** @class */ (function () {
  41521. function ColorCurves() {
  41522. this._dirty = true;
  41523. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41524. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41525. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41526. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41527. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41528. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41529. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41530. this._globalHue = 30;
  41531. this._globalDensity = 0;
  41532. this._globalSaturation = 0;
  41533. this._globalExposure = 0;
  41534. this._highlightsHue = 30;
  41535. this._highlightsDensity = 0;
  41536. this._highlightsSaturation = 0;
  41537. this._highlightsExposure = 0;
  41538. this._midtonesHue = 30;
  41539. this._midtonesDensity = 0;
  41540. this._midtonesSaturation = 0;
  41541. this._midtonesExposure = 0;
  41542. this._shadowsHue = 30;
  41543. this._shadowsDensity = 0;
  41544. this._shadowsSaturation = 0;
  41545. this._shadowsExposure = 0;
  41546. }
  41547. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41548. /**
  41549. * Gets the global Hue value.
  41550. * 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).
  41551. */
  41552. get: function () {
  41553. return this._globalHue;
  41554. },
  41555. /**
  41556. * Sets the global Hue value.
  41557. * 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).
  41558. */
  41559. set: function (value) {
  41560. this._globalHue = value;
  41561. this._dirty = true;
  41562. },
  41563. enumerable: true,
  41564. configurable: true
  41565. });
  41566. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41567. /**
  41568. * Gets the global Density value.
  41569. * 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.
  41570. * Values less than zero provide a filter of opposite hue.
  41571. */
  41572. get: function () {
  41573. return this._globalDensity;
  41574. },
  41575. /**
  41576. * Sets the global Density value.
  41577. * 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.
  41578. * Values less than zero provide a filter of opposite hue.
  41579. */
  41580. set: function (value) {
  41581. this._globalDensity = value;
  41582. this._dirty = true;
  41583. },
  41584. enumerable: true,
  41585. configurable: true
  41586. });
  41587. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41588. /**
  41589. * Gets the global Saturation value.
  41590. * 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.
  41591. */
  41592. get: function () {
  41593. return this._globalSaturation;
  41594. },
  41595. /**
  41596. * Sets the global Saturation value.
  41597. * 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.
  41598. */
  41599. set: function (value) {
  41600. this._globalSaturation = value;
  41601. this._dirty = true;
  41602. },
  41603. enumerable: true,
  41604. configurable: true
  41605. });
  41606. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41607. /**
  41608. * Gets the highlights Hue value.
  41609. * 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).
  41610. */
  41611. get: function () {
  41612. return this._highlightsHue;
  41613. },
  41614. /**
  41615. * Sets the highlights Hue value.
  41616. * 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).
  41617. */
  41618. set: function (value) {
  41619. this._highlightsHue = value;
  41620. this._dirty = true;
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41626. /**
  41627. * Gets the highlights Density value.
  41628. * 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.
  41629. * Values less than zero provide a filter of opposite hue.
  41630. */
  41631. get: function () {
  41632. return this._highlightsDensity;
  41633. },
  41634. /**
  41635. * Sets the highlights Density value.
  41636. * 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.
  41637. * Values less than zero provide a filter of opposite hue.
  41638. */
  41639. set: function (value) {
  41640. this._highlightsDensity = value;
  41641. this._dirty = true;
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41647. /**
  41648. * Gets the highlights Saturation value.
  41649. * 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.
  41650. */
  41651. get: function () {
  41652. return this._highlightsSaturation;
  41653. },
  41654. /**
  41655. * Sets the highlights Saturation value.
  41656. * 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.
  41657. */
  41658. set: function (value) {
  41659. this._highlightsSaturation = value;
  41660. this._dirty = true;
  41661. },
  41662. enumerable: true,
  41663. configurable: true
  41664. });
  41665. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41666. /**
  41667. * Gets the highlights Exposure value.
  41668. * 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.
  41669. */
  41670. get: function () {
  41671. return this._highlightsExposure;
  41672. },
  41673. /**
  41674. * Sets the highlights Exposure value.
  41675. * 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.
  41676. */
  41677. set: function (value) {
  41678. this._highlightsExposure = value;
  41679. this._dirty = true;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41685. /**
  41686. * Gets the midtones Hue value.
  41687. * 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).
  41688. */
  41689. get: function () {
  41690. return this._midtonesHue;
  41691. },
  41692. /**
  41693. * Sets the midtones Hue value.
  41694. * 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).
  41695. */
  41696. set: function (value) {
  41697. this._midtonesHue = value;
  41698. this._dirty = true;
  41699. },
  41700. enumerable: true,
  41701. configurable: true
  41702. });
  41703. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41704. /**
  41705. * Gets the midtones Density value.
  41706. * 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.
  41707. * Values less than zero provide a filter of opposite hue.
  41708. */
  41709. get: function () {
  41710. return this._midtonesDensity;
  41711. },
  41712. /**
  41713. * Sets the midtones Density value.
  41714. * 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.
  41715. * Values less than zero provide a filter of opposite hue.
  41716. */
  41717. set: function (value) {
  41718. this._midtonesDensity = value;
  41719. this._dirty = true;
  41720. },
  41721. enumerable: true,
  41722. configurable: true
  41723. });
  41724. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41725. /**
  41726. * Gets the midtones Saturation value.
  41727. * 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.
  41728. */
  41729. get: function () {
  41730. return this._midtonesSaturation;
  41731. },
  41732. /**
  41733. * Sets the midtones Saturation value.
  41734. * 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.
  41735. */
  41736. set: function (value) {
  41737. this._midtonesSaturation = value;
  41738. this._dirty = true;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41744. /**
  41745. * Gets the midtones Exposure value.
  41746. * 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.
  41747. */
  41748. get: function () {
  41749. return this._midtonesExposure;
  41750. },
  41751. /**
  41752. * Sets the midtones Exposure value.
  41753. * 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.
  41754. */
  41755. set: function (value) {
  41756. this._midtonesExposure = value;
  41757. this._dirty = true;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41763. /**
  41764. * Gets the shadows Hue value.
  41765. * 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).
  41766. */
  41767. get: function () {
  41768. return this._shadowsHue;
  41769. },
  41770. /**
  41771. * Sets the shadows Hue value.
  41772. * 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).
  41773. */
  41774. set: function (value) {
  41775. this._shadowsHue = value;
  41776. this._dirty = true;
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41782. /**
  41783. * Gets the shadows Density value.
  41784. * 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.
  41785. * Values less than zero provide a filter of opposite hue.
  41786. */
  41787. get: function () {
  41788. return this._shadowsDensity;
  41789. },
  41790. /**
  41791. * Sets the shadows Density value.
  41792. * 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.
  41793. * Values less than zero provide a filter of opposite hue.
  41794. */
  41795. set: function (value) {
  41796. this._shadowsDensity = value;
  41797. this._dirty = true;
  41798. },
  41799. enumerable: true,
  41800. configurable: true
  41801. });
  41802. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41803. /**
  41804. * Gets the shadows Saturation value.
  41805. * 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.
  41806. */
  41807. get: function () {
  41808. return this._shadowsSaturation;
  41809. },
  41810. /**
  41811. * Sets the shadows Saturation value.
  41812. * 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.
  41813. */
  41814. set: function (value) {
  41815. this._shadowsSaturation = value;
  41816. this._dirty = true;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41822. /**
  41823. * Gets the shadows Exposure value.
  41824. * 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.
  41825. */
  41826. get: function () {
  41827. return this._shadowsExposure;
  41828. },
  41829. /**
  41830. * Sets the shadows Exposure value.
  41831. * 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.
  41832. */
  41833. set: function (value) {
  41834. this._shadowsExposure = value;
  41835. this._dirty = true;
  41836. },
  41837. enumerable: true,
  41838. configurable: true
  41839. });
  41840. ColorCurves.prototype.getClassName = function () {
  41841. return "ColorCurves";
  41842. };
  41843. /**
  41844. * Binds the color curves to the shader.
  41845. * @param colorCurves The color curve to bind
  41846. * @param effect The effect to bind to
  41847. */
  41848. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41849. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41850. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41851. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41852. if (colorCurves._dirty) {
  41853. colorCurves._dirty = false;
  41854. // Fill in global info.
  41855. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41856. // Compute highlights info.
  41857. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41858. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41859. // Compute midtones info.
  41860. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41861. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41862. // Compute shadows info.
  41863. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41864. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41865. // Compute deltas (neutral is midtones).
  41866. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41867. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41868. }
  41869. if (effect) {
  41870. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41871. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41872. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41873. }
  41874. };
  41875. /**
  41876. * Prepare the list of uniforms associated with the ColorCurves effects.
  41877. * @param uniformsList The list of uniforms used in the effect
  41878. */
  41879. ColorCurves.PrepareUniforms = function (uniformsList) {
  41880. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41881. };
  41882. /**
  41883. * Returns color grading data based on a hue, density, saturation and exposure value.
  41884. * @param filterHue The hue of the color filter.
  41885. * @param filterDensity The density of the color filter.
  41886. * @param saturation The saturation.
  41887. * @param exposure The exposure.
  41888. * @param result The result data container.
  41889. */
  41890. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41891. if (hue == null) {
  41892. return;
  41893. }
  41894. hue = ColorCurves.clamp(hue, 0, 360);
  41895. density = ColorCurves.clamp(density, -100, 100);
  41896. saturation = ColorCurves.clamp(saturation, -100, 100);
  41897. exposure = ColorCurves.clamp(exposure, -100, 100);
  41898. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41899. // so that the maximum filter density is only 50% control. This provides fine control
  41900. // for small values and reasonable range.
  41901. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41902. density *= 0.5;
  41903. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41904. if (density < 0) {
  41905. density *= -1;
  41906. hue = (hue + 180) % 360;
  41907. }
  41908. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41909. result.scaleToRef(2, result);
  41910. result.a = 1 + 0.01 * saturation;
  41911. };
  41912. /**
  41913. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41914. * @param value The input slider value in range [-100,100].
  41915. * @returns Adjusted value.
  41916. */
  41917. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41918. value /= 100;
  41919. var x = Math.abs(value);
  41920. x = Math.pow(x, 2);
  41921. if (value < 0) {
  41922. x *= -1;
  41923. }
  41924. x *= 100;
  41925. return x;
  41926. };
  41927. /**
  41928. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41929. * @param hue The hue (H) input.
  41930. * @param saturation The saturation (S) input.
  41931. * @param brightness The brightness (B) input.
  41932. * @result An RGBA color represented as Vector4.
  41933. */
  41934. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41935. var h = ColorCurves.clamp(hue, 0, 360);
  41936. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41937. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41938. if (s === 0) {
  41939. result.r = v;
  41940. result.g = v;
  41941. result.b = v;
  41942. }
  41943. else {
  41944. // sector 0 to 5
  41945. h /= 60;
  41946. var i = Math.floor(h);
  41947. // fractional part of h
  41948. var f = h - i;
  41949. var p = v * (1 - s);
  41950. var q = v * (1 - s * f);
  41951. var t = v * (1 - s * (1 - f));
  41952. switch (i) {
  41953. case 0:
  41954. result.r = v;
  41955. result.g = t;
  41956. result.b = p;
  41957. break;
  41958. case 1:
  41959. result.r = q;
  41960. result.g = v;
  41961. result.b = p;
  41962. break;
  41963. case 2:
  41964. result.r = p;
  41965. result.g = v;
  41966. result.b = t;
  41967. break;
  41968. case 3:
  41969. result.r = p;
  41970. result.g = q;
  41971. result.b = v;
  41972. break;
  41973. case 4:
  41974. result.r = t;
  41975. result.g = p;
  41976. result.b = v;
  41977. break;
  41978. default: // case 5:
  41979. result.r = v;
  41980. result.g = p;
  41981. result.b = q;
  41982. break;
  41983. }
  41984. }
  41985. result.a = 1;
  41986. };
  41987. /**
  41988. * Returns a value clamped between min and max
  41989. * @param value The value to clamp
  41990. * @param min The minimum of value
  41991. * @param max The maximum of value
  41992. * @returns The clamped value.
  41993. */
  41994. ColorCurves.clamp = function (value, min, max) {
  41995. return Math.min(Math.max(value, min), max);
  41996. };
  41997. /**
  41998. * Clones the current color curve instance.
  41999. * @return The cloned curves
  42000. */
  42001. ColorCurves.prototype.clone = function () {
  42002. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42003. };
  42004. /**
  42005. * Serializes the current color curve instance to a json representation.
  42006. * @return a JSON representation
  42007. */
  42008. ColorCurves.prototype.serialize = function () {
  42009. return BABYLON.SerializationHelper.Serialize(this);
  42010. };
  42011. /**
  42012. * Parses the color curve from a json representation.
  42013. * @param source the JSON source to parse
  42014. * @return The parsed curves
  42015. */
  42016. ColorCurves.Parse = function (source) {
  42017. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42018. };
  42019. __decorate([
  42020. BABYLON.serialize()
  42021. ], ColorCurves.prototype, "_globalHue", void 0);
  42022. __decorate([
  42023. BABYLON.serialize()
  42024. ], ColorCurves.prototype, "_globalDensity", void 0);
  42025. __decorate([
  42026. BABYLON.serialize()
  42027. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42028. __decorate([
  42029. BABYLON.serialize()
  42030. ], ColorCurves.prototype, "_globalExposure", void 0);
  42031. __decorate([
  42032. BABYLON.serialize()
  42033. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42034. __decorate([
  42035. BABYLON.serialize()
  42036. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42037. __decorate([
  42038. BABYLON.serialize()
  42039. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42040. __decorate([
  42041. BABYLON.serialize()
  42042. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42043. __decorate([
  42044. BABYLON.serialize()
  42045. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42046. __decorate([
  42047. BABYLON.serialize()
  42048. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42049. __decorate([
  42050. BABYLON.serialize()
  42051. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42052. __decorate([
  42053. BABYLON.serialize()
  42054. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42055. return ColorCurves;
  42056. }());
  42057. BABYLON.ColorCurves = ColorCurves;
  42058. })(BABYLON || (BABYLON = {}));
  42059. //# sourceMappingURL=babylon.colorCurves.js.map
  42060. //# sourceMappingURL=babylon.behavior.js.map
  42061. var BABYLON;
  42062. (function (BABYLON) {
  42063. /**
  42064. * "Static Class" containing the most commonly used helper while dealing with material for
  42065. * rendering purpose.
  42066. *
  42067. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42068. *
  42069. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42070. */
  42071. var MaterialHelper = /** @class */ (function () {
  42072. function MaterialHelper() {
  42073. }
  42074. /**
  42075. * Bind the current view position to an effect.
  42076. * @param effect The effect to be bound
  42077. * @param scene The scene the eyes position is used from
  42078. */
  42079. MaterialHelper.BindEyePosition = function (effect, scene) {
  42080. if (scene._forcedViewPosition) {
  42081. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42082. return;
  42083. }
  42084. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42085. };
  42086. /**
  42087. * Helps preparing the defines values about the UVs in used in the effect.
  42088. * UVs are shared as much as we can accross chanels in the shaders.
  42089. * @param texture The texture we are preparing the UVs for
  42090. * @param defines The defines to update
  42091. * @param key The chanel key "diffuse", "specular"... used in the shader
  42092. */
  42093. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42094. defines._needUVs = true;
  42095. defines[key] = true;
  42096. if (texture.getTextureMatrix().isIdentity(true)) {
  42097. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42098. if (texture.coordinatesIndex === 0) {
  42099. defines["MAINUV1"] = true;
  42100. }
  42101. else {
  42102. defines["MAINUV2"] = true;
  42103. }
  42104. }
  42105. else {
  42106. defines[key + "DIRECTUV"] = 0;
  42107. }
  42108. };
  42109. /**
  42110. * Binds a texture matrix value to its corrsponding uniform
  42111. * @param texture The texture to bind the matrix for
  42112. * @param uniformBuffer The uniform buffer receivin the data
  42113. * @param key The chanel key "diffuse", "specular"... used in the shader
  42114. */
  42115. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42116. var matrix = texture.getTextureMatrix();
  42117. if (!matrix.isIdentity(true)) {
  42118. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42119. }
  42120. };
  42121. /**
  42122. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42123. * @param mesh defines the current mesh
  42124. * @param scene defines the current scene
  42125. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42126. * @param pointsCloud defines if point cloud rendering has to be turned on
  42127. * @param fogEnabled defines if fog has to be turned on
  42128. * @param alphaTest defines if alpha testing has to be turned on
  42129. * @param defines defines the current list of defines
  42130. */
  42131. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42132. if (defines._areMiscDirty) {
  42133. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42134. defines["POINTSIZE"] = pointsCloud;
  42135. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42136. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42137. defines["ALPHATEST"] = alphaTest;
  42138. }
  42139. };
  42140. /**
  42141. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42142. * @param scene defines the current scene
  42143. * @param engine defines the current engine
  42144. * @param defines specifies the list of active defines
  42145. * @param useInstances defines if instances have to be turned on
  42146. * @param useClipPlane defines if clip plane have to be turned on
  42147. */
  42148. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42149. if (useClipPlane === void 0) { useClipPlane = null; }
  42150. var changed = false;
  42151. if (useClipPlane == null) {
  42152. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42153. }
  42154. if (defines["CLIPPLANE"] !== useClipPlane) {
  42155. defines["CLIPPLANE"] = useClipPlane;
  42156. changed = true;
  42157. }
  42158. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42159. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42160. changed = true;
  42161. }
  42162. if (defines["INSTANCES"] !== useInstances) {
  42163. defines["INSTANCES"] = useInstances;
  42164. changed = true;
  42165. }
  42166. if (changed) {
  42167. defines.markAsUnprocessed();
  42168. }
  42169. };
  42170. /**
  42171. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42172. * @param mesh The mesh containing the geometry data we will draw
  42173. * @param defines The defines to update
  42174. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42175. * @param useBones Precise whether bones should be used or not (override mesh info)
  42176. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42177. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42178. * @returns false if defines are considered not dirty and have not been checked
  42179. */
  42180. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42181. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42182. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42183. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42184. return false;
  42185. }
  42186. defines._normals = defines._needNormals;
  42187. defines._uvs = defines._needUVs;
  42188. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42189. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42190. defines["TANGENT"] = true;
  42191. }
  42192. if (defines._needUVs) {
  42193. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42194. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42195. }
  42196. else {
  42197. defines["UV1"] = false;
  42198. defines["UV2"] = false;
  42199. }
  42200. if (useVertexColor) {
  42201. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42202. defines["VERTEXCOLOR"] = hasVertexColors;
  42203. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42204. }
  42205. if (useBones) {
  42206. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42207. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42208. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42209. }
  42210. else {
  42211. defines["NUM_BONE_INFLUENCERS"] = 0;
  42212. defines["BonesPerMesh"] = 0;
  42213. }
  42214. }
  42215. if (useMorphTargets) {
  42216. var manager = mesh.morphTargetManager;
  42217. if (manager) {
  42218. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42219. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42220. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42221. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42222. }
  42223. else {
  42224. defines["MORPHTARGETS_TANGENT"] = false;
  42225. defines["MORPHTARGETS_NORMAL"] = false;
  42226. defines["MORPHTARGETS"] = false;
  42227. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42228. }
  42229. }
  42230. return true;
  42231. };
  42232. /**
  42233. * Prepares the defines related to the light information passed in parameter
  42234. * @param scene The scene we are intending to draw
  42235. * @param mesh The mesh the effect is compiling for
  42236. * @param defines The defines to update
  42237. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42238. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42239. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42240. * @returns true if normals will be required for the rest of the effect
  42241. */
  42242. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42243. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42244. if (disableLighting === void 0) { disableLighting = false; }
  42245. if (!defines._areLightsDirty) {
  42246. return defines._needNormals;
  42247. }
  42248. var lightIndex = 0;
  42249. var needNormals = false;
  42250. var needRebuild = false;
  42251. var lightmapMode = false;
  42252. var shadowEnabled = false;
  42253. var specularEnabled = false;
  42254. if (scene.lightsEnabled && !disableLighting) {
  42255. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42256. var light = _a[_i];
  42257. needNormals = true;
  42258. if (defines["LIGHT" + lightIndex] === undefined) {
  42259. needRebuild = true;
  42260. }
  42261. defines["LIGHT" + lightIndex] = true;
  42262. defines["SPOTLIGHT" + lightIndex] = false;
  42263. defines["HEMILIGHT" + lightIndex] = false;
  42264. defines["POINTLIGHT" + lightIndex] = false;
  42265. defines["DIRLIGHT" + lightIndex] = false;
  42266. var type;
  42267. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42268. type = "SPOTLIGHT" + lightIndex;
  42269. var spotLight = light;
  42270. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42271. }
  42272. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42273. type = "HEMILIGHT" + lightIndex;
  42274. }
  42275. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42276. type = "POINTLIGHT" + lightIndex;
  42277. }
  42278. else {
  42279. type = "DIRLIGHT" + lightIndex;
  42280. }
  42281. defines[type] = true;
  42282. // Specular
  42283. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42284. specularEnabled = true;
  42285. }
  42286. // Shadows
  42287. defines["SHADOW" + lightIndex] = false;
  42288. defines["SHADOWPCF" + lightIndex] = false;
  42289. defines["SHADOWPCSS" + lightIndex] = false;
  42290. defines["SHADOWPOISSON" + lightIndex] = false;
  42291. defines["SHADOWESM" + lightIndex] = false;
  42292. defines["SHADOWCUBE" + lightIndex] = false;
  42293. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42294. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42295. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42296. var shadowGenerator = light.getShadowGenerator();
  42297. if (shadowGenerator) {
  42298. shadowEnabled = true;
  42299. shadowGenerator.prepareDefines(defines, lightIndex);
  42300. }
  42301. }
  42302. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42303. lightmapMode = true;
  42304. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42305. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42306. }
  42307. else {
  42308. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42309. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42310. }
  42311. lightIndex++;
  42312. if (lightIndex === maxSimultaneousLights)
  42313. break;
  42314. }
  42315. }
  42316. defines["SPECULARTERM"] = specularEnabled;
  42317. defines["SHADOWS"] = shadowEnabled;
  42318. // Resetting all other lights if any
  42319. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42320. if (defines["LIGHT" + index] !== undefined) {
  42321. defines["LIGHT" + index] = false;
  42322. defines["HEMILIGHT" + lightIndex] = false;
  42323. defines["POINTLIGHT" + lightIndex] = false;
  42324. defines["DIRLIGHT" + lightIndex] = false;
  42325. defines["SPOTLIGHT" + lightIndex] = false;
  42326. defines["SHADOW" + lightIndex] = false;
  42327. }
  42328. }
  42329. var caps = scene.getEngine().getCaps();
  42330. if (defines["SHADOWFLOAT"] === undefined) {
  42331. needRebuild = true;
  42332. }
  42333. defines["SHADOWFLOAT"] = shadowEnabled &&
  42334. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42335. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42336. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42337. if (needRebuild) {
  42338. defines.rebuild();
  42339. }
  42340. return needNormals;
  42341. };
  42342. /**
  42343. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42344. * that won t be acctive due to defines being turned off.
  42345. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42346. * @param samplersList The samplers list
  42347. * @param defines The defines helping in the list generation
  42348. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42349. */
  42350. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42351. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42352. var uniformsList;
  42353. var uniformBuffersList = null;
  42354. if (uniformsListOrOptions.uniformsNames) {
  42355. var options = uniformsListOrOptions;
  42356. uniformsList = options.uniformsNames;
  42357. uniformBuffersList = options.uniformBuffersNames;
  42358. samplersList = options.samplers;
  42359. defines = options.defines;
  42360. maxSimultaneousLights = options.maxSimultaneousLights;
  42361. }
  42362. else {
  42363. uniformsList = uniformsListOrOptions;
  42364. if (!samplersList) {
  42365. samplersList = [];
  42366. }
  42367. }
  42368. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42369. if (!defines["LIGHT" + lightIndex]) {
  42370. break;
  42371. }
  42372. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42373. if (uniformBuffersList) {
  42374. uniformBuffersList.push("Light" + lightIndex);
  42375. }
  42376. samplersList.push("shadowSampler" + lightIndex);
  42377. samplersList.push("depthSampler" + lightIndex);
  42378. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42379. samplersList.push("projectionLightSampler" + lightIndex);
  42380. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42381. }
  42382. }
  42383. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42384. uniformsList.push("morphTargetInfluences");
  42385. }
  42386. };
  42387. /**
  42388. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42389. * @param defines The defines to update while falling back
  42390. * @param fallbacks The authorized effect fallbacks
  42391. * @param maxSimultaneousLights The maximum number of lights allowed
  42392. * @param rank the current rank of the Effect
  42393. * @returns The newly affected rank
  42394. */
  42395. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42396. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42397. if (rank === void 0) { rank = 0; }
  42398. var lightFallbackRank = 0;
  42399. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42400. if (!defines["LIGHT" + lightIndex]) {
  42401. break;
  42402. }
  42403. if (lightIndex > 0) {
  42404. lightFallbackRank = rank + lightIndex;
  42405. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42406. }
  42407. if (!defines["SHADOWS"]) {
  42408. if (defines["SHADOW" + lightIndex]) {
  42409. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42410. }
  42411. if (defines["SHADOWPCF" + lightIndex]) {
  42412. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42413. }
  42414. if (defines["SHADOWPCSS" + lightIndex]) {
  42415. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42416. }
  42417. if (defines["SHADOWPOISSON" + lightIndex]) {
  42418. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42419. }
  42420. if (defines["SHADOWESM" + lightIndex]) {
  42421. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42422. }
  42423. }
  42424. }
  42425. return lightFallbackRank++;
  42426. };
  42427. /**
  42428. * Prepares the list of attributes required for morph targets according to the effect defines.
  42429. * @param attribs The current list of supported attribs
  42430. * @param mesh The mesh to prepare the morph targets attributes for
  42431. * @param defines The current Defines of the effect
  42432. */
  42433. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42434. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42435. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42436. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42437. var manager = mesh.morphTargetManager;
  42438. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42439. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42440. for (var index = 0; index < influencers; index++) {
  42441. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42442. if (normal) {
  42443. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42444. }
  42445. if (tangent) {
  42446. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42447. }
  42448. if (attribs.length > maxAttributesCount) {
  42449. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42450. }
  42451. }
  42452. }
  42453. };
  42454. /**
  42455. * Prepares the list of attributes required for bones according to the effect defines.
  42456. * @param attribs The current list of supported attribs
  42457. * @param mesh The mesh to prepare the bones attributes for
  42458. * @param defines The current Defines of the effect
  42459. * @param fallbacks The current efffect fallback strategy
  42460. */
  42461. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42462. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42463. fallbacks.addCPUSkinningFallback(0, mesh);
  42464. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42465. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42466. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42469. }
  42470. }
  42471. };
  42472. /**
  42473. * Prepares the list of attributes required for instances according to the effect defines.
  42474. * @param attribs The current list of supported attribs
  42475. * @param defines The current Defines of the effect
  42476. */
  42477. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42478. if (defines["INSTANCES"]) {
  42479. attribs.push("world0");
  42480. attribs.push("world1");
  42481. attribs.push("world2");
  42482. attribs.push("world3");
  42483. }
  42484. };
  42485. /**
  42486. * Binds the light shadow information to the effect for the given mesh.
  42487. * @param light The light containing the generator
  42488. * @param scene The scene the lights belongs to
  42489. * @param mesh The mesh we are binding the information to render
  42490. * @param lightIndex The light index in the effect used to render the mesh
  42491. * @param effect The effect we are binding the data to
  42492. */
  42493. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42494. if (light.shadowEnabled && mesh.receiveShadows) {
  42495. var shadowGenerator = light.getShadowGenerator();
  42496. if (shadowGenerator) {
  42497. shadowGenerator.bindShadowLight(lightIndex, effect);
  42498. }
  42499. }
  42500. };
  42501. /**
  42502. * Binds the light information to the effect.
  42503. * @param light The light containing the generator
  42504. * @param effect The effect we are binding the data to
  42505. * @param lightIndex The light index in the effect used to render
  42506. */
  42507. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42508. light.transferToEffect(effect, lightIndex + "");
  42509. };
  42510. /**
  42511. * Binds the lights information from the scene to the effect for the given mesh.
  42512. * @param scene The scene the lights belongs to
  42513. * @param mesh The mesh we are binding the information to render
  42514. * @param effect The effect we are binding the data to
  42515. * @param defines The generated defines for the effect
  42516. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42517. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42518. */
  42519. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42520. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42521. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42522. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42523. for (var i = 0; i < len; i++) {
  42524. var light = mesh._lightSources[i];
  42525. var iAsString = i.toString();
  42526. var scaledIntensity = light.getScaledIntensity();
  42527. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42528. MaterialHelper.BindLightProperties(light, effect, i);
  42529. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42530. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42531. if (defines["SPECULARTERM"]) {
  42532. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42533. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42534. }
  42535. // Shadows
  42536. if (scene.shadowsEnabled) {
  42537. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42538. }
  42539. light._uniformBuffer.update();
  42540. }
  42541. };
  42542. /**
  42543. * Binds the fog information from the scene to the effect for the given mesh.
  42544. * @param scene The scene the lights belongs to
  42545. * @param mesh The mesh we are binding the information to render
  42546. * @param effect The effect we are binding the data to
  42547. */
  42548. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42549. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42550. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42551. effect.setColor3("vFogColor", scene.fogColor);
  42552. }
  42553. };
  42554. /**
  42555. * Binds the bones information from the mesh to the effect.
  42556. * @param mesh The mesh we are binding the information to render
  42557. * @param effect The effect we are binding the data to
  42558. */
  42559. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42560. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42561. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42562. if (matrices && effect) {
  42563. effect.setMatrices("mBones", matrices);
  42564. }
  42565. }
  42566. };
  42567. /**
  42568. * Binds the morph targets information from the mesh to the effect.
  42569. * @param abstractMesh The mesh we are binding the information to render
  42570. * @param effect The effect we are binding the data to
  42571. */
  42572. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42573. var manager = abstractMesh.morphTargetManager;
  42574. if (!abstractMesh || !manager) {
  42575. return;
  42576. }
  42577. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42578. };
  42579. /**
  42580. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42581. * @param defines The generated defines used in the effect
  42582. * @param effect The effect we are binding the data to
  42583. * @param scene The scene we are willing to render with logarithmic scale for
  42584. */
  42585. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42586. if (defines["LOGARITHMICDEPTH"]) {
  42587. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42588. }
  42589. };
  42590. /**
  42591. * Binds the clip plane information from the scene to the effect.
  42592. * @param scene The scene the clip plane information are extracted from
  42593. * @param effect The effect we are binding the data to
  42594. */
  42595. MaterialHelper.BindClipPlane = function (effect, scene) {
  42596. if (scene.clipPlane) {
  42597. var clipPlane = scene.clipPlane;
  42598. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42599. }
  42600. };
  42601. return MaterialHelper;
  42602. }());
  42603. BABYLON.MaterialHelper = MaterialHelper;
  42604. })(BABYLON || (BABYLON = {}));
  42605. //# sourceMappingURL=babylon.materialHelper.js.map
  42606. var BABYLON;
  42607. (function (BABYLON) {
  42608. var PushMaterial = /** @class */ (function (_super) {
  42609. __extends(PushMaterial, _super);
  42610. function PushMaterial(name, scene) {
  42611. var _this = _super.call(this, name, scene) || this;
  42612. _this._normalMatrix = new BABYLON.Matrix();
  42613. _this.storeEffectOnSubMeshes = true;
  42614. return _this;
  42615. }
  42616. PushMaterial.prototype.getEffect = function () {
  42617. return this._activeEffect;
  42618. };
  42619. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42620. if (!mesh) {
  42621. return false;
  42622. }
  42623. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42624. return true;
  42625. }
  42626. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42627. };
  42628. /**
  42629. * Binds the given world matrix to the active effect
  42630. *
  42631. * @param world the matrix to bind
  42632. */
  42633. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42634. this._activeEffect.setMatrix("world", world);
  42635. };
  42636. /**
  42637. * Binds the given normal matrix to the active effect
  42638. *
  42639. * @param normalMatrix the matrix to bind
  42640. */
  42641. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42642. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42643. };
  42644. PushMaterial.prototype.bind = function (world, mesh) {
  42645. if (!mesh) {
  42646. return;
  42647. }
  42648. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42649. };
  42650. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42651. if (effect === void 0) { effect = null; }
  42652. _super.prototype._afterBind.call(this, mesh);
  42653. this.getScene()._cachedEffect = effect;
  42654. };
  42655. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42656. if (visibility === void 0) { visibility = 1; }
  42657. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42658. };
  42659. return PushMaterial;
  42660. }(BABYLON.Material));
  42661. BABYLON.PushMaterial = PushMaterial;
  42662. })(BABYLON || (BABYLON = {}));
  42663. //# sourceMappingURL=babylon.pushMaterial.js.map
  42664. var BABYLON;
  42665. (function (BABYLON) {
  42666. /** @hidden */
  42667. var StandardMaterialDefines = /** @class */ (function (_super) {
  42668. __extends(StandardMaterialDefines, _super);
  42669. function StandardMaterialDefines() {
  42670. var _this = _super.call(this) || this;
  42671. _this.MAINUV1 = false;
  42672. _this.MAINUV2 = false;
  42673. _this.DIFFUSE = false;
  42674. _this.DIFFUSEDIRECTUV = 0;
  42675. _this.AMBIENT = false;
  42676. _this.AMBIENTDIRECTUV = 0;
  42677. _this.OPACITY = false;
  42678. _this.OPACITYDIRECTUV = 0;
  42679. _this.OPACITYRGB = false;
  42680. _this.REFLECTION = false;
  42681. _this.EMISSIVE = false;
  42682. _this.EMISSIVEDIRECTUV = 0;
  42683. _this.SPECULAR = false;
  42684. _this.SPECULARDIRECTUV = 0;
  42685. _this.BUMP = false;
  42686. _this.BUMPDIRECTUV = 0;
  42687. _this.PARALLAX = false;
  42688. _this.PARALLAXOCCLUSION = false;
  42689. _this.SPECULAROVERALPHA = false;
  42690. _this.CLIPPLANE = false;
  42691. _this.ALPHATEST = false;
  42692. _this.DEPTHPREPASS = false;
  42693. _this.ALPHAFROMDIFFUSE = false;
  42694. _this.POINTSIZE = false;
  42695. _this.FOG = false;
  42696. _this.SPECULARTERM = false;
  42697. _this.DIFFUSEFRESNEL = false;
  42698. _this.OPACITYFRESNEL = false;
  42699. _this.REFLECTIONFRESNEL = false;
  42700. _this.REFRACTIONFRESNEL = false;
  42701. _this.EMISSIVEFRESNEL = false;
  42702. _this.FRESNEL = false;
  42703. _this.NORMAL = false;
  42704. _this.UV1 = false;
  42705. _this.UV2 = false;
  42706. _this.VERTEXCOLOR = false;
  42707. _this.VERTEXALPHA = false;
  42708. _this.NUM_BONE_INFLUENCERS = 0;
  42709. _this.BonesPerMesh = 0;
  42710. _this.INSTANCES = false;
  42711. _this.GLOSSINESS = false;
  42712. _this.ROUGHNESS = false;
  42713. _this.EMISSIVEASILLUMINATION = false;
  42714. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42715. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42716. _this.LIGHTMAP = false;
  42717. _this.LIGHTMAPDIRECTUV = 0;
  42718. _this.OBJECTSPACE_NORMALMAP = false;
  42719. _this.USELIGHTMAPASSHADOWMAP = false;
  42720. _this.REFLECTIONMAP_3D = false;
  42721. _this.REFLECTIONMAP_SPHERICAL = false;
  42722. _this.REFLECTIONMAP_PLANAR = false;
  42723. _this.REFLECTIONMAP_CUBIC = false;
  42724. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42725. _this.REFLECTIONMAP_PROJECTION = false;
  42726. _this.REFLECTIONMAP_SKYBOX = false;
  42727. _this.REFLECTIONMAP_EXPLICIT = false;
  42728. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42729. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42730. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42731. _this.INVERTCUBICMAP = false;
  42732. _this.LOGARITHMICDEPTH = false;
  42733. _this.REFRACTION = false;
  42734. _this.REFRACTIONMAP_3D = false;
  42735. _this.REFLECTIONOVERALPHA = false;
  42736. _this.TWOSIDEDLIGHTING = false;
  42737. _this.SHADOWFLOAT = false;
  42738. _this.MORPHTARGETS = false;
  42739. _this.MORPHTARGETS_NORMAL = false;
  42740. _this.MORPHTARGETS_TANGENT = false;
  42741. _this.NUM_MORPH_INFLUENCERS = 0;
  42742. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42743. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42744. _this.IMAGEPROCESSING = false;
  42745. _this.VIGNETTE = false;
  42746. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42747. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42748. _this.TONEMAPPING = false;
  42749. _this.CONTRAST = false;
  42750. _this.COLORCURVES = false;
  42751. _this.COLORGRADING = false;
  42752. _this.COLORGRADING3D = false;
  42753. _this.SAMPLER3DGREENDEPTH = false;
  42754. _this.SAMPLER3DBGRMAP = false;
  42755. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42756. /**
  42757. * If the reflection texture on this material is in linear color space
  42758. * @hidden
  42759. */
  42760. _this.IS_REFLECTION_LINEAR = false;
  42761. /**
  42762. * If the refraction texture on this material is in linear color space
  42763. * @hidden
  42764. */
  42765. _this.IS_REFRACTION_LINEAR = false;
  42766. _this.EXPOSURE = false;
  42767. _this.rebuild();
  42768. return _this;
  42769. }
  42770. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42771. var modes = [
  42772. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42773. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42774. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42775. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42776. ];
  42777. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42778. var mode = modes_1[_i];
  42779. this[mode] = (mode === modeToEnable);
  42780. }
  42781. };
  42782. return StandardMaterialDefines;
  42783. }(BABYLON.MaterialDefines));
  42784. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42785. var StandardMaterial = /** @class */ (function (_super) {
  42786. __extends(StandardMaterial, _super);
  42787. function StandardMaterial(name, scene) {
  42788. var _this = _super.call(this, name, scene) || this;
  42789. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42790. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42791. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42792. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42793. _this.specularPower = 64;
  42794. _this._useAlphaFromDiffuseTexture = false;
  42795. _this._useEmissiveAsIllumination = false;
  42796. _this._linkEmissiveWithDiffuse = false;
  42797. _this._useSpecularOverAlpha = false;
  42798. _this._useReflectionOverAlpha = false;
  42799. _this._disableLighting = false;
  42800. _this._useObjectSpaceNormalMap = false;
  42801. _this._useParallax = false;
  42802. _this._useParallaxOcclusion = false;
  42803. _this.parallaxScaleBias = 0.05;
  42804. _this._roughness = 0;
  42805. _this.indexOfRefraction = 0.98;
  42806. _this.invertRefractionY = true;
  42807. /**
  42808. * Defines the alpha limits in alpha test mode
  42809. */
  42810. _this.alphaCutOff = 0.4;
  42811. _this._useLightmapAsShadowmap = false;
  42812. _this._useReflectionFresnelFromSpecular = false;
  42813. _this._useGlossinessFromSpecularMapAlpha = false;
  42814. _this._maxSimultaneousLights = 4;
  42815. /**
  42816. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42817. */
  42818. _this._invertNormalMapX = false;
  42819. /**
  42820. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42821. */
  42822. _this._invertNormalMapY = false;
  42823. /**
  42824. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42825. */
  42826. _this._twoSidedLighting = false;
  42827. _this._renderTargets = new BABYLON.SmartArray(16);
  42828. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42829. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42830. // Setup the default processing configuration to the scene.
  42831. _this._attachImageProcessingConfiguration(null);
  42832. _this.getRenderTargetTextures = function () {
  42833. _this._renderTargets.reset();
  42834. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42835. _this._renderTargets.push(_this._reflectionTexture);
  42836. }
  42837. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42838. _this._renderTargets.push(_this._refractionTexture);
  42839. }
  42840. return _this._renderTargets;
  42841. };
  42842. return _this;
  42843. }
  42844. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42845. /**
  42846. * Gets the image processing configuration used either in this material.
  42847. */
  42848. get: function () {
  42849. return this._imageProcessingConfiguration;
  42850. },
  42851. /**
  42852. * Sets the Default image processing configuration used either in the this material.
  42853. *
  42854. * If sets to null, the scene one is in use.
  42855. */
  42856. set: function (value) {
  42857. this._attachImageProcessingConfiguration(value);
  42858. // Ensure the effect will be rebuilt.
  42859. this._markAllSubMeshesAsTexturesDirty();
  42860. },
  42861. enumerable: true,
  42862. configurable: true
  42863. });
  42864. /**
  42865. * Attaches a new image processing configuration to the Standard Material.
  42866. * @param configuration
  42867. */
  42868. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42869. var _this = this;
  42870. if (configuration === this._imageProcessingConfiguration) {
  42871. return;
  42872. }
  42873. // Detaches observer.
  42874. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42875. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42876. }
  42877. // Pick the scene configuration if needed.
  42878. if (!configuration) {
  42879. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42880. }
  42881. else {
  42882. this._imageProcessingConfiguration = configuration;
  42883. }
  42884. // Attaches observer.
  42885. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42886. _this._markAllSubMeshesAsImageProcessingDirty();
  42887. });
  42888. };
  42889. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42890. /**
  42891. * Gets wether the color curves effect is enabled.
  42892. */
  42893. get: function () {
  42894. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42895. },
  42896. /**
  42897. * Sets wether the color curves effect is enabled.
  42898. */
  42899. set: function (value) {
  42900. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42901. },
  42902. enumerable: true,
  42903. configurable: true
  42904. });
  42905. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42906. /**
  42907. * Gets wether the color grading effect is enabled.
  42908. */
  42909. get: function () {
  42910. return this.imageProcessingConfiguration.colorGradingEnabled;
  42911. },
  42912. /**
  42913. * Gets wether the color grading effect is enabled.
  42914. */
  42915. set: function (value) {
  42916. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42922. /**
  42923. * Gets wether tonemapping is enabled or not.
  42924. */
  42925. get: function () {
  42926. return this._imageProcessingConfiguration.toneMappingEnabled;
  42927. },
  42928. /**
  42929. * Sets wether tonemapping is enabled or not
  42930. */
  42931. set: function (value) {
  42932. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42933. },
  42934. enumerable: true,
  42935. configurable: true
  42936. });
  42937. ;
  42938. ;
  42939. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42940. /**
  42941. * The camera exposure used on this material.
  42942. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42943. * This corresponds to a photographic exposure.
  42944. */
  42945. get: function () {
  42946. return this._imageProcessingConfiguration.exposure;
  42947. },
  42948. /**
  42949. * The camera exposure used on this material.
  42950. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42951. * This corresponds to a photographic exposure.
  42952. */
  42953. set: function (value) {
  42954. this._imageProcessingConfiguration.exposure = value;
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. ;
  42960. ;
  42961. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42962. /**
  42963. * Gets The camera contrast used on this material.
  42964. */
  42965. get: function () {
  42966. return this._imageProcessingConfiguration.contrast;
  42967. },
  42968. /**
  42969. * Sets The camera contrast used on this material.
  42970. */
  42971. set: function (value) {
  42972. this._imageProcessingConfiguration.contrast = value;
  42973. },
  42974. enumerable: true,
  42975. configurable: true
  42976. });
  42977. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42978. /**
  42979. * Gets the Color Grading 2D Lookup Texture.
  42980. */
  42981. get: function () {
  42982. return this._imageProcessingConfiguration.colorGradingTexture;
  42983. },
  42984. /**
  42985. * Sets the Color Grading 2D Lookup Texture.
  42986. */
  42987. set: function (value) {
  42988. this._imageProcessingConfiguration.colorGradingTexture = value;
  42989. },
  42990. enumerable: true,
  42991. configurable: true
  42992. });
  42993. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42994. /**
  42995. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42996. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42997. * 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;
  42998. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42999. */
  43000. get: function () {
  43001. return this._imageProcessingConfiguration.colorCurves;
  43002. },
  43003. /**
  43004. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43005. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43006. * 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;
  43007. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43008. */
  43009. set: function (value) {
  43010. this._imageProcessingConfiguration.colorCurves = value;
  43011. },
  43012. enumerable: true,
  43013. configurable: true
  43014. });
  43015. StandardMaterial.prototype.getClassName = function () {
  43016. return "StandardMaterial";
  43017. };
  43018. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43019. get: function () {
  43020. return this._useLogarithmicDepth;
  43021. },
  43022. set: function (value) {
  43023. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43024. this._markAllSubMeshesAsMiscDirty();
  43025. },
  43026. enumerable: true,
  43027. configurable: true
  43028. });
  43029. StandardMaterial.prototype.needAlphaBlending = function () {
  43030. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43031. };
  43032. StandardMaterial.prototype.needAlphaTesting = function () {
  43033. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43034. };
  43035. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43036. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43037. };
  43038. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43039. return this._diffuseTexture;
  43040. };
  43041. /**
  43042. * Child classes can use it to update shaders
  43043. */
  43044. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43045. if (useInstances === void 0) { useInstances = false; }
  43046. if (subMesh.effect && this.isFrozen) {
  43047. if (this._wasPreviouslyReady && subMesh.effect) {
  43048. return true;
  43049. }
  43050. }
  43051. if (!subMesh._materialDefines) {
  43052. subMesh._materialDefines = new StandardMaterialDefines();
  43053. }
  43054. var scene = this.getScene();
  43055. var defines = subMesh._materialDefines;
  43056. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43057. if (defines._renderId === scene.getRenderId()) {
  43058. return true;
  43059. }
  43060. }
  43061. var engine = scene.getEngine();
  43062. // Lights
  43063. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43064. // Textures
  43065. if (defines._areTexturesDirty) {
  43066. defines._needUVs = false;
  43067. defines.MAINUV1 = false;
  43068. defines.MAINUV2 = false;
  43069. if (scene.texturesEnabled) {
  43070. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43071. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43072. return false;
  43073. }
  43074. else {
  43075. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43076. }
  43077. }
  43078. else {
  43079. defines.DIFFUSE = false;
  43080. }
  43081. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43082. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43083. return false;
  43084. }
  43085. else {
  43086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43087. }
  43088. }
  43089. else {
  43090. defines.AMBIENT = false;
  43091. }
  43092. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43093. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43094. return false;
  43095. }
  43096. else {
  43097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43098. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43099. }
  43100. }
  43101. else {
  43102. defines.OPACITY = false;
  43103. }
  43104. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43105. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43106. return false;
  43107. }
  43108. else {
  43109. defines._needNormals = true;
  43110. defines.REFLECTION = true;
  43111. defines.ROUGHNESS = (this._roughness > 0);
  43112. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43113. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43114. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43115. switch (this._reflectionTexture.coordinatesMode) {
  43116. case BABYLON.Texture.EXPLICIT_MODE:
  43117. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43118. break;
  43119. case BABYLON.Texture.PLANAR_MODE:
  43120. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43121. break;
  43122. case BABYLON.Texture.PROJECTION_MODE:
  43123. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43124. break;
  43125. case BABYLON.Texture.SKYBOX_MODE:
  43126. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43127. break;
  43128. case BABYLON.Texture.SPHERICAL_MODE:
  43129. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43130. break;
  43131. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43132. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43133. break;
  43134. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43135. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43136. break;
  43137. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43138. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43139. break;
  43140. case BABYLON.Texture.CUBIC_MODE:
  43141. case BABYLON.Texture.INVCUBIC_MODE:
  43142. default:
  43143. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43144. break;
  43145. }
  43146. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43147. }
  43148. }
  43149. else {
  43150. defines.REFLECTION = false;
  43151. }
  43152. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43153. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43154. return false;
  43155. }
  43156. else {
  43157. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43158. }
  43159. }
  43160. else {
  43161. defines.EMISSIVE = false;
  43162. }
  43163. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43164. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43165. return false;
  43166. }
  43167. else {
  43168. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43169. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43170. }
  43171. }
  43172. else {
  43173. defines.LIGHTMAP = false;
  43174. }
  43175. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43176. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43177. return false;
  43178. }
  43179. else {
  43180. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43181. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43182. }
  43183. }
  43184. else {
  43185. defines.SPECULAR = false;
  43186. }
  43187. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43188. // Bump texure can not be not blocking.
  43189. if (!this._bumpTexture.isReady()) {
  43190. return false;
  43191. }
  43192. else {
  43193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43194. defines.PARALLAX = this._useParallax;
  43195. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43196. }
  43197. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43198. }
  43199. else {
  43200. defines.BUMP = false;
  43201. }
  43202. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43203. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43204. return false;
  43205. }
  43206. else {
  43207. defines._needUVs = true;
  43208. defines.REFRACTION = true;
  43209. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43210. }
  43211. }
  43212. else {
  43213. defines.REFRACTION = false;
  43214. }
  43215. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43216. }
  43217. else {
  43218. defines.DIFFUSE = false;
  43219. defines.AMBIENT = false;
  43220. defines.OPACITY = false;
  43221. defines.REFLECTION = false;
  43222. defines.EMISSIVE = false;
  43223. defines.LIGHTMAP = false;
  43224. defines.BUMP = false;
  43225. defines.REFRACTION = false;
  43226. }
  43227. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43228. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43229. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43230. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43231. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43232. }
  43233. if (defines._areImageProcessingDirty) {
  43234. if (!this._imageProcessingConfiguration.isReady()) {
  43235. return false;
  43236. }
  43237. this._imageProcessingConfiguration.prepareDefines(defines);
  43238. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43239. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43240. }
  43241. if (defines._areFresnelDirty) {
  43242. if (StandardMaterial.FresnelEnabled) {
  43243. // Fresnel
  43244. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43245. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43246. this._reflectionFresnelParameters) {
  43247. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43248. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43249. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43250. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43251. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43252. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43253. defines._needNormals = true;
  43254. defines.FRESNEL = true;
  43255. }
  43256. }
  43257. else {
  43258. defines.FRESNEL = false;
  43259. }
  43260. }
  43261. // Misc.
  43262. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43263. // Attribs
  43264. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43265. // Values that need to be evaluated on every frame
  43266. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43267. // Get correct effect
  43268. if (defines.isDirty) {
  43269. defines.markAsProcessed();
  43270. scene.resetCachedMaterial();
  43271. // Fallbacks
  43272. var fallbacks = new BABYLON.EffectFallbacks();
  43273. if (defines.REFLECTION) {
  43274. fallbacks.addFallback(0, "REFLECTION");
  43275. }
  43276. if (defines.SPECULAR) {
  43277. fallbacks.addFallback(0, "SPECULAR");
  43278. }
  43279. if (defines.BUMP) {
  43280. fallbacks.addFallback(0, "BUMP");
  43281. }
  43282. if (defines.PARALLAX) {
  43283. fallbacks.addFallback(1, "PARALLAX");
  43284. }
  43285. if (defines.PARALLAXOCCLUSION) {
  43286. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43287. }
  43288. if (defines.SPECULAROVERALPHA) {
  43289. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43290. }
  43291. if (defines.FOG) {
  43292. fallbacks.addFallback(1, "FOG");
  43293. }
  43294. if (defines.POINTSIZE) {
  43295. fallbacks.addFallback(0, "POINTSIZE");
  43296. }
  43297. if (defines.LOGARITHMICDEPTH) {
  43298. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43299. }
  43300. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43301. if (defines.SPECULARTERM) {
  43302. fallbacks.addFallback(0, "SPECULARTERM");
  43303. }
  43304. if (defines.DIFFUSEFRESNEL) {
  43305. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43306. }
  43307. if (defines.OPACITYFRESNEL) {
  43308. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43309. }
  43310. if (defines.REFLECTIONFRESNEL) {
  43311. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43312. }
  43313. if (defines.EMISSIVEFRESNEL) {
  43314. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43315. }
  43316. if (defines.FRESNEL) {
  43317. fallbacks.addFallback(4, "FRESNEL");
  43318. }
  43319. //Attributes
  43320. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43321. if (defines.NORMAL) {
  43322. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43323. }
  43324. if (defines.UV1) {
  43325. attribs.push(BABYLON.VertexBuffer.UVKind);
  43326. }
  43327. if (defines.UV2) {
  43328. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43329. }
  43330. if (defines.VERTEXCOLOR) {
  43331. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43332. }
  43333. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43334. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43335. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43336. var shaderName = "default";
  43337. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43338. "vFogInfos", "vFogColor", "pointSize",
  43339. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43340. "mBones",
  43341. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43342. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43343. "vReflectionPosition", "vReflectionSize",
  43344. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43345. ];
  43346. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43347. var uniformBuffers = ["Material", "Scene"];
  43348. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43349. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43350. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43351. uniformsNames: uniforms,
  43352. uniformBuffersNames: uniformBuffers,
  43353. samplers: samplers,
  43354. defines: defines,
  43355. maxSimultaneousLights: this._maxSimultaneousLights
  43356. });
  43357. if (this.customShaderNameResolve) {
  43358. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43359. }
  43360. var join = defines.toString();
  43361. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43362. attributes: attribs,
  43363. uniformsNames: uniforms,
  43364. uniformBuffersNames: uniformBuffers,
  43365. samplers: samplers,
  43366. defines: join,
  43367. fallbacks: fallbacks,
  43368. onCompiled: this.onCompiled,
  43369. onError: this.onError,
  43370. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43371. }, engine), defines);
  43372. this.buildUniformLayout();
  43373. }
  43374. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43375. return false;
  43376. }
  43377. defines._renderId = scene.getRenderId();
  43378. this._wasPreviouslyReady = true;
  43379. return true;
  43380. };
  43381. StandardMaterial.prototype.buildUniformLayout = function () {
  43382. // Order is important !
  43383. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43384. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43385. this._uniformBuffer.addUniform("opacityParts", 4);
  43386. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43387. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43388. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43389. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43390. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43391. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43392. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43393. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43394. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43395. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43396. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43397. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43398. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43399. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43400. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43401. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43402. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43403. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43404. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43405. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43406. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43407. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43408. this._uniformBuffer.addUniform("specularMatrix", 16);
  43409. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43410. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43411. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43412. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43413. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43414. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43415. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43416. this._uniformBuffer.addUniform("pointSize", 1);
  43417. this._uniformBuffer.create();
  43418. };
  43419. StandardMaterial.prototype.unbind = function () {
  43420. if (this._activeEffect) {
  43421. var needFlag = false;
  43422. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43423. this._activeEffect.setTexture("reflection2DSampler", null);
  43424. needFlag = true;
  43425. }
  43426. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43427. this._activeEffect.setTexture("refraction2DSampler", null);
  43428. needFlag = true;
  43429. }
  43430. if (needFlag) {
  43431. this._markAllSubMeshesAsTexturesDirty();
  43432. }
  43433. }
  43434. _super.prototype.unbind.call(this);
  43435. };
  43436. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43437. var scene = this.getScene();
  43438. var defines = subMesh._materialDefines;
  43439. if (!defines) {
  43440. return;
  43441. }
  43442. var effect = subMesh.effect;
  43443. if (!effect) {
  43444. return;
  43445. }
  43446. this._activeEffect = effect;
  43447. // Matrices
  43448. this.bindOnlyWorldMatrix(world);
  43449. // Normal Matrix
  43450. if (defines.OBJECTSPACE_NORMALMAP) {
  43451. world.toNormalMatrix(this._normalMatrix);
  43452. this.bindOnlyNormalMatrix(this._normalMatrix);
  43453. }
  43454. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43455. // Bones
  43456. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43457. if (mustRebind) {
  43458. this._uniformBuffer.bindToEffect(effect, "Material");
  43459. this.bindViewProjection(effect);
  43460. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43461. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43462. // Fresnel
  43463. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43464. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43465. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43466. }
  43467. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43468. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43469. }
  43470. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43471. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43472. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43473. }
  43474. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43475. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43476. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43477. }
  43478. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43479. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43480. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43481. }
  43482. }
  43483. // Textures
  43484. if (scene.texturesEnabled) {
  43485. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43486. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43487. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43488. if (this._diffuseTexture.hasAlpha) {
  43489. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43490. }
  43491. }
  43492. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43493. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43494. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43495. }
  43496. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43497. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43498. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43499. }
  43500. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43501. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43502. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43503. if (this._reflectionTexture.boundingBoxSize) {
  43504. var cubeTexture = this._reflectionTexture;
  43505. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43506. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43507. }
  43508. }
  43509. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43510. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43511. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43512. }
  43513. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43514. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43515. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43516. }
  43517. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43518. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43519. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43520. }
  43521. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43522. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43523. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43524. if (scene._mirroredCameraPosition) {
  43525. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43526. }
  43527. else {
  43528. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43529. }
  43530. }
  43531. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43532. var depth = 1.0;
  43533. if (!this._refractionTexture.isCube) {
  43534. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43535. if (this._refractionTexture.depth) {
  43536. depth = this._refractionTexture.depth;
  43537. }
  43538. }
  43539. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43540. }
  43541. }
  43542. // Point size
  43543. if (this.pointsCloud) {
  43544. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43545. }
  43546. if (defines.SPECULARTERM) {
  43547. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43548. }
  43549. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43550. // Diffuse
  43551. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43552. }
  43553. // Textures
  43554. if (scene.texturesEnabled) {
  43555. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43556. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43557. }
  43558. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43559. effect.setTexture("ambientSampler", this._ambientTexture);
  43560. }
  43561. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43562. effect.setTexture("opacitySampler", this._opacityTexture);
  43563. }
  43564. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43565. if (this._reflectionTexture.isCube) {
  43566. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43567. }
  43568. else {
  43569. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43570. }
  43571. }
  43572. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43573. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43574. }
  43575. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43576. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43577. }
  43578. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43579. effect.setTexture("specularSampler", this._specularTexture);
  43580. }
  43581. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43582. effect.setTexture("bumpSampler", this._bumpTexture);
  43583. }
  43584. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43585. var depth = 1.0;
  43586. if (this._refractionTexture.isCube) {
  43587. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43588. }
  43589. else {
  43590. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43591. }
  43592. }
  43593. }
  43594. // Clip plane
  43595. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43596. // Colors
  43597. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43598. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43599. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43600. }
  43601. if (mustRebind || !this.isFrozen) {
  43602. // Lights
  43603. if (scene.lightsEnabled && !this._disableLighting) {
  43604. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43605. }
  43606. // View
  43607. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43608. this.bindView(effect);
  43609. }
  43610. // Fog
  43611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43612. // Morph targets
  43613. if (defines.NUM_MORPH_INFLUENCERS) {
  43614. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43615. }
  43616. // Log. depth
  43617. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43618. // image processing
  43619. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43620. this._imageProcessingConfiguration.bind(this._activeEffect);
  43621. }
  43622. }
  43623. this._uniformBuffer.update();
  43624. this._afterBind(mesh, this._activeEffect);
  43625. };
  43626. StandardMaterial.prototype.getAnimatables = function () {
  43627. var results = [];
  43628. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43629. results.push(this._diffuseTexture);
  43630. }
  43631. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43632. results.push(this._ambientTexture);
  43633. }
  43634. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43635. results.push(this._opacityTexture);
  43636. }
  43637. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43638. results.push(this._reflectionTexture);
  43639. }
  43640. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43641. results.push(this._emissiveTexture);
  43642. }
  43643. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43644. results.push(this._specularTexture);
  43645. }
  43646. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43647. results.push(this._bumpTexture);
  43648. }
  43649. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43650. results.push(this._lightmapTexture);
  43651. }
  43652. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43653. results.push(this._refractionTexture);
  43654. }
  43655. return results;
  43656. };
  43657. StandardMaterial.prototype.getActiveTextures = function () {
  43658. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43659. if (this._diffuseTexture) {
  43660. activeTextures.push(this._diffuseTexture);
  43661. }
  43662. if (this._ambientTexture) {
  43663. activeTextures.push(this._ambientTexture);
  43664. }
  43665. if (this._opacityTexture) {
  43666. activeTextures.push(this._opacityTexture);
  43667. }
  43668. if (this._reflectionTexture) {
  43669. activeTextures.push(this._reflectionTexture);
  43670. }
  43671. if (this._emissiveTexture) {
  43672. activeTextures.push(this._emissiveTexture);
  43673. }
  43674. if (this._specularTexture) {
  43675. activeTextures.push(this._specularTexture);
  43676. }
  43677. if (this._bumpTexture) {
  43678. activeTextures.push(this._bumpTexture);
  43679. }
  43680. if (this._lightmapTexture) {
  43681. activeTextures.push(this._lightmapTexture);
  43682. }
  43683. if (this._refractionTexture) {
  43684. activeTextures.push(this._refractionTexture);
  43685. }
  43686. return activeTextures;
  43687. };
  43688. StandardMaterial.prototype.hasTexture = function (texture) {
  43689. if (_super.prototype.hasTexture.call(this, texture)) {
  43690. return true;
  43691. }
  43692. if (this._diffuseTexture === texture) {
  43693. return true;
  43694. }
  43695. if (this._ambientTexture === texture) {
  43696. return true;
  43697. }
  43698. if (this._opacityTexture === texture) {
  43699. return true;
  43700. }
  43701. if (this._reflectionTexture === texture) {
  43702. return true;
  43703. }
  43704. if (this._emissiveTexture === texture) {
  43705. return true;
  43706. }
  43707. if (this._specularTexture === texture) {
  43708. return true;
  43709. }
  43710. if (this._bumpTexture === texture) {
  43711. return true;
  43712. }
  43713. if (this._lightmapTexture === texture) {
  43714. return true;
  43715. }
  43716. if (this._refractionTexture === texture) {
  43717. return true;
  43718. }
  43719. return false;
  43720. };
  43721. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43722. if (forceDisposeTextures) {
  43723. if (this._diffuseTexture) {
  43724. this._diffuseTexture.dispose();
  43725. }
  43726. if (this._ambientTexture) {
  43727. this._ambientTexture.dispose();
  43728. }
  43729. if (this._opacityTexture) {
  43730. this._opacityTexture.dispose();
  43731. }
  43732. if (this._reflectionTexture) {
  43733. this._reflectionTexture.dispose();
  43734. }
  43735. if (this._emissiveTexture) {
  43736. this._emissiveTexture.dispose();
  43737. }
  43738. if (this._specularTexture) {
  43739. this._specularTexture.dispose();
  43740. }
  43741. if (this._bumpTexture) {
  43742. this._bumpTexture.dispose();
  43743. }
  43744. if (this._lightmapTexture) {
  43745. this._lightmapTexture.dispose();
  43746. }
  43747. if (this._refractionTexture) {
  43748. this._refractionTexture.dispose();
  43749. }
  43750. }
  43751. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43752. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43753. }
  43754. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43755. };
  43756. StandardMaterial.prototype.clone = function (name) {
  43757. var _this = this;
  43758. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43759. result.name = name;
  43760. result.id = name;
  43761. return result;
  43762. };
  43763. StandardMaterial.prototype.serialize = function () {
  43764. return BABYLON.SerializationHelper.Serialize(this);
  43765. };
  43766. // Statics
  43767. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43768. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43769. };
  43770. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43771. get: function () {
  43772. return StandardMaterial._DiffuseTextureEnabled;
  43773. },
  43774. set: function (value) {
  43775. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43776. return;
  43777. }
  43778. StandardMaterial._DiffuseTextureEnabled = value;
  43779. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43780. },
  43781. enumerable: true,
  43782. configurable: true
  43783. });
  43784. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43785. get: function () {
  43786. return StandardMaterial._AmbientTextureEnabled;
  43787. },
  43788. set: function (value) {
  43789. if (StandardMaterial._AmbientTextureEnabled === value) {
  43790. return;
  43791. }
  43792. StandardMaterial._AmbientTextureEnabled = value;
  43793. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43799. get: function () {
  43800. return StandardMaterial._OpacityTextureEnabled;
  43801. },
  43802. set: function (value) {
  43803. if (StandardMaterial._OpacityTextureEnabled === value) {
  43804. return;
  43805. }
  43806. StandardMaterial._OpacityTextureEnabled = value;
  43807. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43808. },
  43809. enumerable: true,
  43810. configurable: true
  43811. });
  43812. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43813. get: function () {
  43814. return StandardMaterial._ReflectionTextureEnabled;
  43815. },
  43816. set: function (value) {
  43817. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43818. return;
  43819. }
  43820. StandardMaterial._ReflectionTextureEnabled = value;
  43821. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43822. },
  43823. enumerable: true,
  43824. configurable: true
  43825. });
  43826. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43827. get: function () {
  43828. return StandardMaterial._EmissiveTextureEnabled;
  43829. },
  43830. set: function (value) {
  43831. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43832. return;
  43833. }
  43834. StandardMaterial._EmissiveTextureEnabled = value;
  43835. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43836. },
  43837. enumerable: true,
  43838. configurable: true
  43839. });
  43840. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43841. get: function () {
  43842. return StandardMaterial._SpecularTextureEnabled;
  43843. },
  43844. set: function (value) {
  43845. if (StandardMaterial._SpecularTextureEnabled === value) {
  43846. return;
  43847. }
  43848. StandardMaterial._SpecularTextureEnabled = value;
  43849. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43850. },
  43851. enumerable: true,
  43852. configurable: true
  43853. });
  43854. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43855. get: function () {
  43856. return StandardMaterial._BumpTextureEnabled;
  43857. },
  43858. set: function (value) {
  43859. if (StandardMaterial._BumpTextureEnabled === value) {
  43860. return;
  43861. }
  43862. StandardMaterial._BumpTextureEnabled = value;
  43863. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43864. },
  43865. enumerable: true,
  43866. configurable: true
  43867. });
  43868. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43869. get: function () {
  43870. return StandardMaterial._LightmapTextureEnabled;
  43871. },
  43872. set: function (value) {
  43873. if (StandardMaterial._LightmapTextureEnabled === value) {
  43874. return;
  43875. }
  43876. StandardMaterial._LightmapTextureEnabled = value;
  43877. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43878. },
  43879. enumerable: true,
  43880. configurable: true
  43881. });
  43882. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43883. get: function () {
  43884. return StandardMaterial._RefractionTextureEnabled;
  43885. },
  43886. set: function (value) {
  43887. if (StandardMaterial._RefractionTextureEnabled === value) {
  43888. return;
  43889. }
  43890. StandardMaterial._RefractionTextureEnabled = value;
  43891. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43897. get: function () {
  43898. return StandardMaterial._ColorGradingTextureEnabled;
  43899. },
  43900. set: function (value) {
  43901. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43902. return;
  43903. }
  43904. StandardMaterial._ColorGradingTextureEnabled = value;
  43905. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43906. },
  43907. enumerable: true,
  43908. configurable: true
  43909. });
  43910. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43911. get: function () {
  43912. return StandardMaterial._FresnelEnabled;
  43913. },
  43914. set: function (value) {
  43915. if (StandardMaterial._FresnelEnabled === value) {
  43916. return;
  43917. }
  43918. StandardMaterial._FresnelEnabled = value;
  43919. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43920. },
  43921. enumerable: true,
  43922. configurable: true
  43923. });
  43924. // Flags used to enable or disable a type of texture for all Standard Materials
  43925. StandardMaterial._DiffuseTextureEnabled = true;
  43926. StandardMaterial._AmbientTextureEnabled = true;
  43927. StandardMaterial._OpacityTextureEnabled = true;
  43928. StandardMaterial._ReflectionTextureEnabled = true;
  43929. StandardMaterial._EmissiveTextureEnabled = true;
  43930. StandardMaterial._SpecularTextureEnabled = true;
  43931. StandardMaterial._BumpTextureEnabled = true;
  43932. StandardMaterial._LightmapTextureEnabled = true;
  43933. StandardMaterial._RefractionTextureEnabled = true;
  43934. StandardMaterial._ColorGradingTextureEnabled = true;
  43935. StandardMaterial._FresnelEnabled = true;
  43936. __decorate([
  43937. BABYLON.serializeAsTexture("diffuseTexture")
  43938. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43939. __decorate([
  43940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43941. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43942. __decorate([
  43943. BABYLON.serializeAsTexture("ambientTexture")
  43944. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43945. __decorate([
  43946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43947. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43948. __decorate([
  43949. BABYLON.serializeAsTexture("opacityTexture")
  43950. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43951. __decorate([
  43952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43953. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43954. __decorate([
  43955. BABYLON.serializeAsTexture("reflectionTexture")
  43956. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43957. __decorate([
  43958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43959. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43960. __decorate([
  43961. BABYLON.serializeAsTexture("emissiveTexture")
  43962. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43963. __decorate([
  43964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43965. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43966. __decorate([
  43967. BABYLON.serializeAsTexture("specularTexture")
  43968. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43969. __decorate([
  43970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43971. ], StandardMaterial.prototype, "specularTexture", void 0);
  43972. __decorate([
  43973. BABYLON.serializeAsTexture("bumpTexture")
  43974. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43975. __decorate([
  43976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43977. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43978. __decorate([
  43979. BABYLON.serializeAsTexture("lightmapTexture")
  43980. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43981. __decorate([
  43982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43983. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43984. __decorate([
  43985. BABYLON.serializeAsTexture("refractionTexture")
  43986. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43987. __decorate([
  43988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43989. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43990. __decorate([
  43991. BABYLON.serializeAsColor3("ambient")
  43992. ], StandardMaterial.prototype, "ambientColor", void 0);
  43993. __decorate([
  43994. BABYLON.serializeAsColor3("diffuse")
  43995. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43996. __decorate([
  43997. BABYLON.serializeAsColor3("specular")
  43998. ], StandardMaterial.prototype, "specularColor", void 0);
  43999. __decorate([
  44000. BABYLON.serializeAsColor3("emissive")
  44001. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44002. __decorate([
  44003. BABYLON.serialize()
  44004. ], StandardMaterial.prototype, "specularPower", void 0);
  44005. __decorate([
  44006. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44007. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44008. __decorate([
  44009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44010. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44011. __decorate([
  44012. BABYLON.serialize("useEmissiveAsIllumination")
  44013. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44014. __decorate([
  44015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44016. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44017. __decorate([
  44018. BABYLON.serialize("linkEmissiveWithDiffuse")
  44019. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44020. __decorate([
  44021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44022. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44023. __decorate([
  44024. BABYLON.serialize("useSpecularOverAlpha")
  44025. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44026. __decorate([
  44027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44028. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44029. __decorate([
  44030. BABYLON.serialize("useReflectionOverAlpha")
  44031. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44032. __decorate([
  44033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44034. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44035. __decorate([
  44036. BABYLON.serialize("disableLighting")
  44037. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44038. __decorate([
  44039. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44040. ], StandardMaterial.prototype, "disableLighting", void 0);
  44041. __decorate([
  44042. BABYLON.serialize("useObjectSpaceNormalMap")
  44043. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44044. __decorate([
  44045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44046. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44047. __decorate([
  44048. BABYLON.serialize("useParallax")
  44049. ], StandardMaterial.prototype, "_useParallax", void 0);
  44050. __decorate([
  44051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44052. ], StandardMaterial.prototype, "useParallax", void 0);
  44053. __decorate([
  44054. BABYLON.serialize("useParallaxOcclusion")
  44055. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44056. __decorate([
  44057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44058. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44059. __decorate([
  44060. BABYLON.serialize()
  44061. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44062. __decorate([
  44063. BABYLON.serialize("roughness")
  44064. ], StandardMaterial.prototype, "_roughness", void 0);
  44065. __decorate([
  44066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44067. ], StandardMaterial.prototype, "roughness", void 0);
  44068. __decorate([
  44069. BABYLON.serialize()
  44070. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44071. __decorate([
  44072. BABYLON.serialize()
  44073. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44074. __decorate([
  44075. BABYLON.serialize()
  44076. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44077. __decorate([
  44078. BABYLON.serialize("useLightmapAsShadowmap")
  44079. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44080. __decorate([
  44081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44082. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44083. __decorate([
  44084. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44085. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44086. __decorate([
  44087. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44088. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44089. __decorate([
  44090. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44091. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44092. __decorate([
  44093. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44094. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44095. __decorate([
  44096. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44097. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44098. __decorate([
  44099. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44100. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44101. __decorate([
  44102. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44103. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44104. __decorate([
  44105. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44106. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44107. __decorate([
  44108. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44109. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44110. __decorate([
  44111. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44112. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44113. __decorate([
  44114. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44115. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44116. __decorate([
  44117. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44118. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44119. __decorate([
  44120. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44121. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44122. __decorate([
  44123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44124. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44125. __decorate([
  44126. BABYLON.serialize("maxSimultaneousLights")
  44127. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44128. __decorate([
  44129. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44130. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44131. __decorate([
  44132. BABYLON.serialize("invertNormalMapX")
  44133. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44134. __decorate([
  44135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44136. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44137. __decorate([
  44138. BABYLON.serialize("invertNormalMapY")
  44139. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44140. __decorate([
  44141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44142. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44143. __decorate([
  44144. BABYLON.serialize("twoSidedLighting")
  44145. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44146. __decorate([
  44147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44148. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44149. __decorate([
  44150. BABYLON.serialize()
  44151. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44152. return StandardMaterial;
  44153. }(BABYLON.PushMaterial));
  44154. BABYLON.StandardMaterial = StandardMaterial;
  44155. })(BABYLON || (BABYLON = {}));
  44156. //# sourceMappingURL=babylon.standardMaterial.js.map
  44157. var BABYLON;
  44158. (function (BABYLON) {
  44159. /**
  44160. * Manages the defines for the PBR Material.
  44161. * @hiddenChildren
  44162. */
  44163. var PBRMaterialDefines = /** @class */ (function (_super) {
  44164. __extends(PBRMaterialDefines, _super);
  44165. /**
  44166. * Initializes the PBR Material defines.
  44167. */
  44168. function PBRMaterialDefines() {
  44169. var _this = _super.call(this) || this;
  44170. _this.PBR = true;
  44171. _this.MAINUV1 = false;
  44172. _this.MAINUV2 = false;
  44173. _this.UV1 = false;
  44174. _this.UV2 = false;
  44175. _this.ALBEDO = false;
  44176. _this.ALBEDODIRECTUV = 0;
  44177. _this.VERTEXCOLOR = false;
  44178. _this.AMBIENT = false;
  44179. _this.AMBIENTDIRECTUV = 0;
  44180. _this.AMBIENTINGRAYSCALE = false;
  44181. _this.OPACITY = false;
  44182. _this.VERTEXALPHA = false;
  44183. _this.OPACITYDIRECTUV = 0;
  44184. _this.OPACITYRGB = false;
  44185. _this.ALPHATEST = false;
  44186. _this.DEPTHPREPASS = false;
  44187. _this.ALPHABLEND = false;
  44188. _this.ALPHAFROMALBEDO = false;
  44189. _this.ALPHATESTVALUE = "0.5";
  44190. _this.SPECULAROVERALPHA = false;
  44191. _this.RADIANCEOVERALPHA = false;
  44192. _this.ALPHAFRESNEL = false;
  44193. _this.LINEARALPHAFRESNEL = false;
  44194. _this.PREMULTIPLYALPHA = false;
  44195. _this.EMISSIVE = false;
  44196. _this.EMISSIVEDIRECTUV = 0;
  44197. _this.REFLECTIVITY = false;
  44198. _this.REFLECTIVITYDIRECTUV = 0;
  44199. _this.SPECULARTERM = false;
  44200. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44201. _this.MICROSURFACEAUTOMATIC = false;
  44202. _this.LODBASEDMICROSFURACE = false;
  44203. _this.MICROSURFACEMAP = false;
  44204. _this.MICROSURFACEMAPDIRECTUV = 0;
  44205. _this.METALLICWORKFLOW = false;
  44206. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44207. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44208. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44209. _this.AOSTOREINMETALMAPRED = false;
  44210. _this.ENVIRONMENTBRDF = false;
  44211. _this.NORMAL = false;
  44212. _this.TANGENT = false;
  44213. _this.BUMP = false;
  44214. _this.BUMPDIRECTUV = 0;
  44215. _this.OBJECTSPACE_NORMALMAP = false;
  44216. _this.PARALLAX = false;
  44217. _this.PARALLAXOCCLUSION = false;
  44218. _this.NORMALXYSCALE = true;
  44219. _this.LIGHTMAP = false;
  44220. _this.LIGHTMAPDIRECTUV = 0;
  44221. _this.USELIGHTMAPASSHADOWMAP = false;
  44222. _this.GAMMALIGHTMAP = false;
  44223. _this.REFLECTION = false;
  44224. _this.REFLECTIONMAP_3D = false;
  44225. _this.REFLECTIONMAP_SPHERICAL = false;
  44226. _this.REFLECTIONMAP_PLANAR = false;
  44227. _this.REFLECTIONMAP_CUBIC = false;
  44228. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44229. _this.REFLECTIONMAP_PROJECTION = false;
  44230. _this.REFLECTIONMAP_SKYBOX = false;
  44231. _this.REFLECTIONMAP_EXPLICIT = false;
  44232. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44233. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44234. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44235. _this.INVERTCUBICMAP = false;
  44236. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44237. _this.USESPHERICALINVERTEX = false;
  44238. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44239. _this.LODINREFLECTIONALPHA = false;
  44240. _this.GAMMAREFLECTION = false;
  44241. _this.RADIANCEOCCLUSION = false;
  44242. _this.HORIZONOCCLUSION = false;
  44243. _this.REFRACTION = false;
  44244. _this.REFRACTIONMAP_3D = false;
  44245. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44246. _this.LODINREFRACTIONALPHA = false;
  44247. _this.GAMMAREFRACTION = false;
  44248. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44249. _this.INSTANCES = false;
  44250. _this.NUM_BONE_INFLUENCERS = 0;
  44251. _this.BonesPerMesh = 0;
  44252. _this.NONUNIFORMSCALING = false;
  44253. _this.MORPHTARGETS = false;
  44254. _this.MORPHTARGETS_NORMAL = false;
  44255. _this.MORPHTARGETS_TANGENT = false;
  44256. _this.NUM_MORPH_INFLUENCERS = 0;
  44257. _this.IMAGEPROCESSING = false;
  44258. _this.VIGNETTE = false;
  44259. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44260. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44261. _this.TONEMAPPING = false;
  44262. _this.CONTRAST = false;
  44263. _this.COLORCURVES = false;
  44264. _this.COLORGRADING = false;
  44265. _this.COLORGRADING3D = false;
  44266. _this.SAMPLER3DGREENDEPTH = false;
  44267. _this.SAMPLER3DBGRMAP = false;
  44268. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44269. _this.EXPOSURE = false;
  44270. _this.USEPHYSICALLIGHTFALLOFF = false;
  44271. _this.TWOSIDEDLIGHTING = false;
  44272. _this.SHADOWFLOAT = false;
  44273. _this.CLIPPLANE = false;
  44274. _this.POINTSIZE = false;
  44275. _this.FOG = false;
  44276. _this.LOGARITHMICDEPTH = false;
  44277. _this.FORCENORMALFORWARD = false;
  44278. _this.SPECULARAA = false;
  44279. _this.UNLIT = false;
  44280. _this.rebuild();
  44281. return _this;
  44282. }
  44283. /**
  44284. * Resets the PBR Material defines.
  44285. */
  44286. PBRMaterialDefines.prototype.reset = function () {
  44287. _super.prototype.reset.call(this);
  44288. this.ALPHATESTVALUE = "0.5";
  44289. this.PBR = true;
  44290. };
  44291. return PBRMaterialDefines;
  44292. }(BABYLON.MaterialDefines));
  44293. /**
  44294. * The Physically based material base class of BJS.
  44295. *
  44296. * This offers the main features of a standard PBR material.
  44297. * For more information, please refer to the documentation :
  44298. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44299. */
  44300. var PBRBaseMaterial = /** @class */ (function (_super) {
  44301. __extends(PBRBaseMaterial, _super);
  44302. /**
  44303. * Instantiates a new PBRMaterial instance.
  44304. *
  44305. * @param name The material name
  44306. * @param scene The scene the material will be use in.
  44307. */
  44308. function PBRBaseMaterial(name, scene) {
  44309. var _this = _super.call(this, name, scene) || this;
  44310. /**
  44311. * Intensity of the direct lights e.g. the four lights available in your scene.
  44312. * This impacts both the direct diffuse and specular highlights.
  44313. */
  44314. _this._directIntensity = 1.0;
  44315. /**
  44316. * Intensity of the emissive part of the material.
  44317. * This helps controlling the emissive effect without modifying the emissive color.
  44318. */
  44319. _this._emissiveIntensity = 1.0;
  44320. /**
  44321. * Intensity of the environment e.g. how much the environment will light the object
  44322. * either through harmonics for rough material or through the refelction for shiny ones.
  44323. */
  44324. _this._environmentIntensity = 1.0;
  44325. /**
  44326. * This is a special control allowing the reduction of the specular highlights coming from the
  44327. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44328. */
  44329. _this._specularIntensity = 1.0;
  44330. /**
  44331. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44332. */
  44333. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44334. /**
  44335. * Debug Control allowing disabling the bump map on this material.
  44336. */
  44337. _this._disableBumpMap = false;
  44338. /**
  44339. * AKA Occlusion Texture Intensity in other nomenclature.
  44340. */
  44341. _this._ambientTextureStrength = 1.0;
  44342. /**
  44343. * The color of a material in ambient lighting.
  44344. */
  44345. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44346. /**
  44347. * AKA Diffuse Color in other nomenclature.
  44348. */
  44349. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44350. /**
  44351. * AKA Specular Color in other nomenclature.
  44352. */
  44353. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44354. /**
  44355. * The color applied when light is reflected from a material.
  44356. */
  44357. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44358. /**
  44359. * The color applied when light is emitted from a material.
  44360. */
  44361. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44362. /**
  44363. * AKA Glossiness in other nomenclature.
  44364. */
  44365. _this._microSurface = 0.9;
  44366. /**
  44367. * source material index of refraction (IOR)' / 'destination material IOR.
  44368. */
  44369. _this._indexOfRefraction = 0.66;
  44370. /**
  44371. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44372. */
  44373. _this._invertRefractionY = false;
  44374. /**
  44375. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44376. * Materials half opaque for instance using refraction could benefit from this control.
  44377. */
  44378. _this._linkRefractionWithTransparency = false;
  44379. /**
  44380. * Specifies that the material will use the light map as a show map.
  44381. */
  44382. _this._useLightmapAsShadowmap = false;
  44383. /**
  44384. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44385. * makes the reflect vector face the model (under horizon).
  44386. */
  44387. _this._useHorizonOcclusion = true;
  44388. /**
  44389. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44390. * too much the area relying on ambient texture to define their ambient occlusion.
  44391. */
  44392. _this._useRadianceOcclusion = true;
  44393. /**
  44394. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44395. */
  44396. _this._useAlphaFromAlbedoTexture = false;
  44397. /**
  44398. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44399. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44400. */
  44401. _this._useSpecularOverAlpha = true;
  44402. /**
  44403. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44404. */
  44405. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44406. /**
  44407. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44408. */
  44409. _this._useRoughnessFromMetallicTextureAlpha = true;
  44410. /**
  44411. * Specifies if the metallic texture contains the roughness information in its green channel.
  44412. */
  44413. _this._useRoughnessFromMetallicTextureGreen = false;
  44414. /**
  44415. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44416. */
  44417. _this._useMetallnessFromMetallicTextureBlue = false;
  44418. /**
  44419. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44420. */
  44421. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44422. /**
  44423. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44424. */
  44425. _this._useAmbientInGrayScale = false;
  44426. /**
  44427. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44428. * The material will try to infer what glossiness each pixel should be.
  44429. */
  44430. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44431. /**
  44432. * BJS is using an harcoded light falloff based on a manually sets up range.
  44433. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44434. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44435. */
  44436. _this._usePhysicalLightFalloff = true;
  44437. /**
  44438. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44439. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44440. */
  44441. _this._useRadianceOverAlpha = true;
  44442. /**
  44443. * Allows using an object space normal map (instead of tangent space).
  44444. */
  44445. _this._useObjectSpaceNormalMap = false;
  44446. /**
  44447. * Allows using the bump map in parallax mode.
  44448. */
  44449. _this._useParallax = false;
  44450. /**
  44451. * Allows using the bump map in parallax occlusion mode.
  44452. */
  44453. _this._useParallaxOcclusion = false;
  44454. /**
  44455. * Controls the scale bias of the parallax mode.
  44456. */
  44457. _this._parallaxScaleBias = 0.05;
  44458. /**
  44459. * If sets to true, disables all the lights affecting the material.
  44460. */
  44461. _this._disableLighting = false;
  44462. /**
  44463. * Number of Simultaneous lights allowed on the material.
  44464. */
  44465. _this._maxSimultaneousLights = 4;
  44466. /**
  44467. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44468. */
  44469. _this._invertNormalMapX = false;
  44470. /**
  44471. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44472. */
  44473. _this._invertNormalMapY = false;
  44474. /**
  44475. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44476. */
  44477. _this._twoSidedLighting = false;
  44478. /**
  44479. * Defines the alpha limits in alpha test mode.
  44480. */
  44481. _this._alphaCutOff = 0.4;
  44482. /**
  44483. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44484. */
  44485. _this._forceAlphaTest = false;
  44486. /**
  44487. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44488. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44489. */
  44490. _this._useAlphaFresnel = false;
  44491. /**
  44492. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44493. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44494. */
  44495. _this._useLinearAlphaFresnel = false;
  44496. /**
  44497. * The transparency mode of the material.
  44498. */
  44499. _this._transparencyMode = null;
  44500. /**
  44501. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44502. * from cos thetav and roughness:
  44503. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44504. */
  44505. _this._environmentBRDFTexture = null;
  44506. /**
  44507. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44508. */
  44509. _this._forceIrradianceInFragment = false;
  44510. /**
  44511. * Force normal to face away from face.
  44512. */
  44513. _this._forceNormalForward = false;
  44514. /**
  44515. * Enables specular anti aliasing in the PBR shader.
  44516. * It will both interacts on the Geometry for analytical and IBL lighting.
  44517. * It also prefilter the roughness map based on the bump values.
  44518. */
  44519. _this._enableSpecularAntiAliasing = false;
  44520. /**
  44521. * Stores the available render targets.
  44522. */
  44523. _this._renderTargets = new BABYLON.SmartArray(16);
  44524. /**
  44525. * Sets the global ambient color for the material used in lighting calculations.
  44526. */
  44527. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44528. /**
  44529. * If set to true, no lighting calculations will be applied.
  44530. */
  44531. _this._unlit = false;
  44532. // Setup the default processing configuration to the scene.
  44533. _this._attachImageProcessingConfiguration(null);
  44534. _this.getRenderTargetTextures = function () {
  44535. _this._renderTargets.reset();
  44536. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44537. _this._renderTargets.push(_this._reflectionTexture);
  44538. }
  44539. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44540. _this._renderTargets.push(_this._refractionTexture);
  44541. }
  44542. return _this._renderTargets;
  44543. };
  44544. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44545. return _this;
  44546. }
  44547. /**
  44548. * Attaches a new image processing configuration to the PBR Material.
  44549. * @param configuration
  44550. */
  44551. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44552. var _this = this;
  44553. if (configuration === this._imageProcessingConfiguration) {
  44554. return;
  44555. }
  44556. // Detaches observer.
  44557. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44558. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44559. }
  44560. // Pick the scene configuration if needed.
  44561. if (!configuration) {
  44562. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44563. }
  44564. else {
  44565. this._imageProcessingConfiguration = configuration;
  44566. }
  44567. // Attaches observer.
  44568. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44569. _this._markAllSubMeshesAsImageProcessingDirty();
  44570. });
  44571. };
  44572. /**
  44573. * Gets the name of the material class.
  44574. */
  44575. PBRBaseMaterial.prototype.getClassName = function () {
  44576. return "PBRBaseMaterial";
  44577. };
  44578. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44579. /**
  44580. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44581. */
  44582. get: function () {
  44583. return this._useLogarithmicDepth;
  44584. },
  44585. /**
  44586. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44587. */
  44588. set: function (value) {
  44589. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44590. },
  44591. enumerable: true,
  44592. configurable: true
  44593. });
  44594. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44595. /**
  44596. * Gets the current transparency mode.
  44597. */
  44598. get: function () {
  44599. return this._transparencyMode;
  44600. },
  44601. /**
  44602. * Sets the transparency mode of the material.
  44603. */
  44604. set: function (value) {
  44605. if (this._transparencyMode === value) {
  44606. return;
  44607. }
  44608. this._transparencyMode = value;
  44609. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44610. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44611. },
  44612. enumerable: true,
  44613. configurable: true
  44614. });
  44615. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44616. /**
  44617. * Returns true if alpha blending should be disabled.
  44618. */
  44619. get: function () {
  44620. return (this._linkRefractionWithTransparency ||
  44621. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44622. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. /**
  44628. * Specifies whether or not this material should be rendered in alpha blend mode.
  44629. */
  44630. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44631. if (this._disableAlphaBlending) {
  44632. return false;
  44633. }
  44634. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44635. };
  44636. /**
  44637. * Specifies if the mesh will require alpha blending.
  44638. * @param mesh - BJS mesh.
  44639. */
  44640. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44641. if (this._disableAlphaBlending) {
  44642. return false;
  44643. }
  44644. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44645. };
  44646. /**
  44647. * Specifies whether or not this material should be rendered in alpha test mode.
  44648. */
  44649. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44650. if (this._forceAlphaTest) {
  44651. return true;
  44652. }
  44653. if (this._linkRefractionWithTransparency) {
  44654. return false;
  44655. }
  44656. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44657. };
  44658. /**
  44659. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44660. */
  44661. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44662. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44663. };
  44664. /**
  44665. * Gets the texture used for the alpha test.
  44666. */
  44667. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44668. return this._albedoTexture;
  44669. };
  44670. /**
  44671. * Specifies that the submesh is ready to be used.
  44672. * @param mesh - BJS mesh.
  44673. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44674. * @param useInstances - Specifies that instances should be used.
  44675. * @returns - boolean indicating that the submesh is ready or not.
  44676. */
  44677. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44678. if (subMesh.effect && this.isFrozen) {
  44679. if (this._wasPreviouslyReady) {
  44680. return true;
  44681. }
  44682. }
  44683. if (!subMesh._materialDefines) {
  44684. subMesh._materialDefines = new PBRMaterialDefines();
  44685. }
  44686. var defines = subMesh._materialDefines;
  44687. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44688. if (defines._renderId === this.getScene().getRenderId()) {
  44689. return true;
  44690. }
  44691. }
  44692. var scene = this.getScene();
  44693. var engine = scene.getEngine();
  44694. if (defines._areTexturesDirty) {
  44695. if (scene.texturesEnabled) {
  44696. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44697. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44698. return false;
  44699. }
  44700. }
  44701. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44702. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44703. return false;
  44704. }
  44705. }
  44706. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44707. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44708. return false;
  44709. }
  44710. }
  44711. var reflectionTexture = this._getReflectionTexture();
  44712. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44713. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44714. return false;
  44715. }
  44716. }
  44717. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44718. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44719. return false;
  44720. }
  44721. }
  44722. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44723. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44724. return false;
  44725. }
  44726. }
  44727. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44728. if (this._metallicTexture) {
  44729. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44730. return false;
  44731. }
  44732. }
  44733. else if (this._reflectivityTexture) {
  44734. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44735. return false;
  44736. }
  44737. }
  44738. if (this._microSurfaceTexture) {
  44739. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44740. return false;
  44741. }
  44742. }
  44743. }
  44744. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44745. // Bump texture cannot be not blocking.
  44746. if (!this._bumpTexture.isReady()) {
  44747. return false;
  44748. }
  44749. }
  44750. var refractionTexture = this._getRefractionTexture();
  44751. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44752. if (!refractionTexture.isReadyOrNotBlocking()) {
  44753. return false;
  44754. }
  44755. }
  44756. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44757. // This is blocking.
  44758. if (!this._environmentBRDFTexture.isReady()) {
  44759. return false;
  44760. }
  44761. }
  44762. }
  44763. }
  44764. if (defines._areImageProcessingDirty) {
  44765. if (!this._imageProcessingConfiguration.isReady()) {
  44766. return false;
  44767. }
  44768. }
  44769. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44770. mesh.createNormals(true);
  44771. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44772. }
  44773. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44774. if (effect) {
  44775. scene.resetCachedMaterial();
  44776. subMesh.setEffect(effect, defines);
  44777. this.buildUniformLayout();
  44778. }
  44779. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44780. return false;
  44781. }
  44782. defines._renderId = scene.getRenderId();
  44783. this._wasPreviouslyReady = true;
  44784. return true;
  44785. };
  44786. /**
  44787. * Specifies if the material uses metallic roughness workflow.
  44788. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44789. */
  44790. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44791. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44792. return true;
  44793. }
  44794. return false;
  44795. };
  44796. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44797. if (onCompiled === void 0) { onCompiled = null; }
  44798. if (onError === void 0) { onError = null; }
  44799. if (useInstances === void 0) { useInstances = null; }
  44800. if (useClipPlane === void 0) { useClipPlane = null; }
  44801. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44802. if (!defines.isDirty) {
  44803. return null;
  44804. }
  44805. defines.markAsProcessed();
  44806. var scene = this.getScene();
  44807. var engine = scene.getEngine();
  44808. // Fallbacks
  44809. var fallbacks = new BABYLON.EffectFallbacks();
  44810. var fallbackRank = 0;
  44811. if (defines.USESPHERICALINVERTEX) {
  44812. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44813. }
  44814. if (defines.FOG) {
  44815. fallbacks.addFallback(fallbackRank, "FOG");
  44816. }
  44817. if (defines.SPECULARAA) {
  44818. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44819. }
  44820. if (defines.POINTSIZE) {
  44821. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44822. }
  44823. if (defines.LOGARITHMICDEPTH) {
  44824. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44825. }
  44826. if (defines.PARALLAX) {
  44827. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44828. }
  44829. if (defines.PARALLAXOCCLUSION) {
  44830. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44831. }
  44832. if (defines.ENVIRONMENTBRDF) {
  44833. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44834. }
  44835. if (defines.TANGENT) {
  44836. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44837. }
  44838. if (defines.BUMP) {
  44839. fallbacks.addFallback(fallbackRank++, "BUMP");
  44840. }
  44841. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44842. if (defines.SPECULARTERM) {
  44843. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44844. }
  44845. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44846. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44847. }
  44848. if (defines.LIGHTMAP) {
  44849. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44850. }
  44851. if (defines.NORMAL) {
  44852. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44853. }
  44854. if (defines.AMBIENT) {
  44855. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44856. }
  44857. if (defines.EMISSIVE) {
  44858. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44859. }
  44860. if (defines.VERTEXCOLOR) {
  44861. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44862. }
  44863. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44864. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44865. }
  44866. if (defines.MORPHTARGETS) {
  44867. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44868. }
  44869. //Attributes
  44870. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44871. if (defines.NORMAL) {
  44872. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44873. }
  44874. if (defines.TANGENT) {
  44875. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44876. }
  44877. if (defines.UV1) {
  44878. attribs.push(BABYLON.VertexBuffer.UVKind);
  44879. }
  44880. if (defines.UV2) {
  44881. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44882. }
  44883. if (defines.VERTEXCOLOR) {
  44884. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44885. }
  44886. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44887. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44888. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44889. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44890. "vFogInfos", "vFogColor", "pointSize",
  44891. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44892. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44893. "mBones",
  44894. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44895. "vLightingIntensity",
  44896. "logarithmicDepthConstant",
  44897. "vSphericalX", "vSphericalY", "vSphericalZ",
  44898. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44899. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44900. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44901. "vTangentSpaceParams"
  44902. ];
  44903. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44904. "bumpSampler", "lightmapSampler", "opacitySampler",
  44905. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44906. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44907. "microSurfaceSampler", "environmentBrdfSampler"];
  44908. var uniformBuffers = ["Material", "Scene"];
  44909. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44910. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44911. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44912. uniformsNames: uniforms,
  44913. uniformBuffersNames: uniformBuffers,
  44914. samplers: samplers,
  44915. defines: defines,
  44916. maxSimultaneousLights: this._maxSimultaneousLights
  44917. });
  44918. var join = defines.toString();
  44919. return engine.createEffect("pbr", {
  44920. attributes: attribs,
  44921. uniformsNames: uniforms,
  44922. uniformBuffersNames: uniformBuffers,
  44923. samplers: samplers,
  44924. defines: join,
  44925. fallbacks: fallbacks,
  44926. onCompiled: onCompiled,
  44927. onError: onError,
  44928. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44929. }, engine);
  44930. };
  44931. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44932. if (useInstances === void 0) { useInstances = null; }
  44933. if (useClipPlane === void 0) { useClipPlane = null; }
  44934. var scene = this.getScene();
  44935. var engine = scene.getEngine();
  44936. // Lights
  44937. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44938. defines._needNormals = true;
  44939. // Textures
  44940. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44941. if (defines._areTexturesDirty) {
  44942. defines._needUVs = false;
  44943. if (scene.texturesEnabled) {
  44944. if (scene.getEngine().getCaps().textureLOD) {
  44945. defines.LODBASEDMICROSFURACE = true;
  44946. }
  44947. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44949. }
  44950. else {
  44951. defines.ALBEDO = false;
  44952. }
  44953. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44955. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44956. }
  44957. else {
  44958. defines.AMBIENT = false;
  44959. }
  44960. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44961. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44962. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44963. }
  44964. else {
  44965. defines.OPACITY = false;
  44966. }
  44967. var reflectionTexture = this._getReflectionTexture();
  44968. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44969. defines.REFLECTION = true;
  44970. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44971. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44972. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44973. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44974. defines.INVERTCUBICMAP = true;
  44975. }
  44976. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44977. switch (reflectionTexture.coordinatesMode) {
  44978. case BABYLON.Texture.EXPLICIT_MODE:
  44979. defines.REFLECTIONMAP_EXPLICIT = true;
  44980. break;
  44981. case BABYLON.Texture.PLANAR_MODE:
  44982. defines.REFLECTIONMAP_PLANAR = true;
  44983. break;
  44984. case BABYLON.Texture.PROJECTION_MODE:
  44985. defines.REFLECTIONMAP_PROJECTION = true;
  44986. break;
  44987. case BABYLON.Texture.SKYBOX_MODE:
  44988. defines.REFLECTIONMAP_SKYBOX = true;
  44989. break;
  44990. case BABYLON.Texture.SPHERICAL_MODE:
  44991. defines.REFLECTIONMAP_SPHERICAL = true;
  44992. break;
  44993. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44994. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44995. break;
  44996. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44997. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44998. break;
  44999. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45000. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45001. break;
  45002. case BABYLON.Texture.CUBIC_MODE:
  45003. case BABYLON.Texture.INVCUBIC_MODE:
  45004. default:
  45005. defines.REFLECTIONMAP_CUBIC = true;
  45006. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45007. break;
  45008. }
  45009. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45010. if (reflectionTexture.sphericalPolynomial) {
  45011. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45012. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45013. defines.USESPHERICALINVERTEX = false;
  45014. }
  45015. else {
  45016. defines.USESPHERICALINVERTEX = true;
  45017. }
  45018. }
  45019. }
  45020. }
  45021. else {
  45022. defines.REFLECTION = false;
  45023. defines.REFLECTIONMAP_3D = false;
  45024. defines.REFLECTIONMAP_SPHERICAL = false;
  45025. defines.REFLECTIONMAP_PLANAR = false;
  45026. defines.REFLECTIONMAP_CUBIC = false;
  45027. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45028. defines.REFLECTIONMAP_PROJECTION = false;
  45029. defines.REFLECTIONMAP_SKYBOX = false;
  45030. defines.REFLECTIONMAP_EXPLICIT = false;
  45031. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45032. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45033. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45034. defines.INVERTCUBICMAP = false;
  45035. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45036. defines.USESPHERICALINVERTEX = false;
  45037. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45038. defines.LODINREFLECTIONALPHA = false;
  45039. defines.GAMMAREFLECTION = false;
  45040. }
  45041. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45043. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45044. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45045. }
  45046. else {
  45047. defines.LIGHTMAP = false;
  45048. }
  45049. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45050. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45051. }
  45052. else {
  45053. defines.EMISSIVE = false;
  45054. }
  45055. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45056. if (this._metallicTexture) {
  45057. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45058. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45059. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45060. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45061. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45062. }
  45063. else if (this._reflectivityTexture) {
  45064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45065. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45066. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45067. }
  45068. else {
  45069. defines.REFLECTIVITY = false;
  45070. }
  45071. if (this._microSurfaceTexture) {
  45072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45073. }
  45074. else {
  45075. defines.MICROSURFACEMAP = false;
  45076. }
  45077. }
  45078. else {
  45079. defines.REFLECTIVITY = false;
  45080. defines.MICROSURFACEMAP = false;
  45081. }
  45082. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45084. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45085. defines.PARALLAX = true;
  45086. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45087. }
  45088. else {
  45089. defines.PARALLAX = false;
  45090. }
  45091. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45092. }
  45093. else {
  45094. defines.BUMP = false;
  45095. }
  45096. var refractionTexture = this._getRefractionTexture();
  45097. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45098. defines.REFRACTION = true;
  45099. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45100. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45101. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45102. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45103. if (this._linkRefractionWithTransparency) {
  45104. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45105. }
  45106. }
  45107. else {
  45108. defines.REFRACTION = false;
  45109. }
  45110. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45111. defines.ENVIRONMENTBRDF = true;
  45112. }
  45113. else {
  45114. defines.ENVIRONMENTBRDF = false;
  45115. }
  45116. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45117. defines.ALPHAFROMALBEDO = true;
  45118. }
  45119. else {
  45120. defines.ALPHAFROMALBEDO = false;
  45121. }
  45122. }
  45123. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45124. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45125. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45126. if (!this.backFaceCulling && this._twoSidedLighting) {
  45127. defines.TWOSIDEDLIGHTING = true;
  45128. }
  45129. else {
  45130. defines.TWOSIDEDLIGHTING = false;
  45131. }
  45132. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45133. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45134. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45135. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45136. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45137. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45138. }
  45139. if (defines._areImageProcessingDirty) {
  45140. this._imageProcessingConfiguration.prepareDefines(defines);
  45141. }
  45142. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45143. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45144. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45145. // Misc.
  45146. if (defines._areMiscDirty) {
  45147. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45148. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45149. }
  45150. // Values that need to be evaluated on every frame
  45151. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45152. // Attribs
  45153. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45154. };
  45155. /**
  45156. * Force shader compilation
  45157. */
  45158. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45159. var _this = this;
  45160. var localOptions = __assign({ clipPlane: false }, options);
  45161. var defines = new PBRMaterialDefines();
  45162. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45163. if (effect.isReady()) {
  45164. if (onCompiled) {
  45165. onCompiled(this);
  45166. }
  45167. }
  45168. else {
  45169. effect.onCompileObservable.add(function () {
  45170. if (onCompiled) {
  45171. onCompiled(_this);
  45172. }
  45173. });
  45174. }
  45175. };
  45176. /**
  45177. * Initializes the uniform buffer layout for the shader.
  45178. */
  45179. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45180. // Order is important !
  45181. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45182. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45183. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45184. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45185. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45186. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45187. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45188. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45189. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45190. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45191. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45192. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45193. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45194. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45195. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45196. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45197. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45198. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45199. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45200. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45201. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45202. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45203. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45204. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45205. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45206. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45207. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45208. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45209. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45210. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45211. this._uniformBuffer.addUniform("pointSize", 1);
  45212. this._uniformBuffer.create();
  45213. };
  45214. /**
  45215. * Unbinds the textures.
  45216. */
  45217. PBRBaseMaterial.prototype.unbind = function () {
  45218. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45219. this._uniformBuffer.setTexture("reflectionSampler", null);
  45220. }
  45221. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45222. this._uniformBuffer.setTexture("refractionSampler", null);
  45223. }
  45224. _super.prototype.unbind.call(this);
  45225. };
  45226. /**
  45227. * Binds the submesh data.
  45228. * @param world - The world matrix.
  45229. * @param mesh - The BJS mesh.
  45230. * @param subMesh - A submesh of the BJS mesh.
  45231. */
  45232. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45233. var scene = this.getScene();
  45234. var defines = subMesh._materialDefines;
  45235. if (!defines) {
  45236. return;
  45237. }
  45238. var effect = subMesh.effect;
  45239. if (!effect) {
  45240. return;
  45241. }
  45242. this._activeEffect = effect;
  45243. // Matrices
  45244. this.bindOnlyWorldMatrix(world);
  45245. // Normal Matrix
  45246. if (defines.OBJECTSPACE_NORMALMAP) {
  45247. world.toNormalMatrix(this._normalMatrix);
  45248. this.bindOnlyNormalMatrix(this._normalMatrix);
  45249. }
  45250. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45251. // Bones
  45252. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45253. var reflectionTexture = null;
  45254. if (mustRebind) {
  45255. this._uniformBuffer.bindToEffect(effect, "Material");
  45256. this.bindViewProjection(effect);
  45257. reflectionTexture = this._getReflectionTexture();
  45258. var refractionTexture = this._getRefractionTexture();
  45259. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45260. // Texture uniforms
  45261. if (scene.texturesEnabled) {
  45262. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45263. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45264. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45265. }
  45266. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45267. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45268. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45269. }
  45270. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45271. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45272. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45273. }
  45274. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45275. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45276. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45277. if (reflectionTexture.boundingBoxSize) {
  45278. var cubeTexture = reflectionTexture;
  45279. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45280. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45281. }
  45282. var polynomials = reflectionTexture.sphericalPolynomial;
  45283. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45284. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45285. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45286. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45287. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45288. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45289. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45290. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45291. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45292. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45293. }
  45294. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45295. }
  45296. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45297. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45298. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45299. }
  45300. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45301. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45302. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45303. }
  45304. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45305. if (this._metallicTexture) {
  45306. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45307. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45308. }
  45309. else if (this._reflectivityTexture) {
  45310. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45311. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45312. }
  45313. if (this._microSurfaceTexture) {
  45314. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45315. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45316. }
  45317. }
  45318. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45319. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45320. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45321. if (scene._mirroredCameraPosition) {
  45322. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45323. }
  45324. else {
  45325. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45326. }
  45327. }
  45328. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45329. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45330. var depth = 1.0;
  45331. if (!refractionTexture.isCube) {
  45332. if (refractionTexture.depth) {
  45333. depth = refractionTexture.depth;
  45334. }
  45335. }
  45336. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45337. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45338. }
  45339. }
  45340. // Point size
  45341. if (this.pointsCloud) {
  45342. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45343. }
  45344. // Colors
  45345. if (defines.METALLICWORKFLOW) {
  45346. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45347. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45348. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45349. }
  45350. else {
  45351. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45352. }
  45353. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45354. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45355. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45356. // Misc
  45357. this._lightingInfos.x = this._directIntensity;
  45358. this._lightingInfos.y = this._emissiveIntensity;
  45359. this._lightingInfos.z = this._environmentIntensity;
  45360. this._lightingInfos.w = this._specularIntensity;
  45361. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45362. }
  45363. // Textures
  45364. if (scene.texturesEnabled) {
  45365. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45366. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45367. }
  45368. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45369. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45370. }
  45371. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45372. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45373. }
  45374. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45375. if (defines.LODBASEDMICROSFURACE) {
  45376. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45377. }
  45378. else {
  45379. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45380. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45381. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45382. }
  45383. }
  45384. if (defines.ENVIRONMENTBRDF) {
  45385. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45386. }
  45387. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45388. if (defines.LODBASEDMICROSFURACE) {
  45389. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45390. }
  45391. else {
  45392. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45393. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45394. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45395. }
  45396. }
  45397. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45398. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45399. }
  45400. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45401. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45402. }
  45403. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45404. if (this._metallicTexture) {
  45405. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45406. }
  45407. else if (this._reflectivityTexture) {
  45408. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45409. }
  45410. if (this._microSurfaceTexture) {
  45411. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45412. }
  45413. }
  45414. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45415. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45416. }
  45417. }
  45418. // Clip plane
  45419. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45420. // Colors
  45421. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45422. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45423. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45424. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45425. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45426. }
  45427. if (mustRebind || !this.isFrozen) {
  45428. // Lights
  45429. if (scene.lightsEnabled && !this._disableLighting) {
  45430. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45431. }
  45432. // View
  45433. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45434. this.bindView(effect);
  45435. }
  45436. // Fog
  45437. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45438. // Morph targets
  45439. if (defines.NUM_MORPH_INFLUENCERS) {
  45440. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45441. }
  45442. // image processing
  45443. this._imageProcessingConfiguration.bind(this._activeEffect);
  45444. // Log. depth
  45445. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45446. }
  45447. this._uniformBuffer.update();
  45448. this._afterBind(mesh, this._activeEffect);
  45449. };
  45450. /**
  45451. * Returns the animatable textures.
  45452. * @returns - Array of animatable textures.
  45453. */
  45454. PBRBaseMaterial.prototype.getAnimatables = function () {
  45455. var results = [];
  45456. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45457. results.push(this._albedoTexture);
  45458. }
  45459. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45460. results.push(this._ambientTexture);
  45461. }
  45462. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45463. results.push(this._opacityTexture);
  45464. }
  45465. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45466. results.push(this._reflectionTexture);
  45467. }
  45468. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45469. results.push(this._emissiveTexture);
  45470. }
  45471. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45472. results.push(this._metallicTexture);
  45473. }
  45474. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45475. results.push(this._reflectivityTexture);
  45476. }
  45477. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45478. results.push(this._bumpTexture);
  45479. }
  45480. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45481. results.push(this._lightmapTexture);
  45482. }
  45483. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45484. results.push(this._refractionTexture);
  45485. }
  45486. return results;
  45487. };
  45488. /**
  45489. * Returns the texture used for reflections.
  45490. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45491. */
  45492. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45493. if (this._reflectionTexture) {
  45494. return this._reflectionTexture;
  45495. }
  45496. return this.getScene().environmentTexture;
  45497. };
  45498. /**
  45499. * Returns the texture used for refraction or null if none is used.
  45500. * @returns - Refection texture if present. If no refraction texture and refraction
  45501. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45502. */
  45503. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45504. if (this._refractionTexture) {
  45505. return this._refractionTexture;
  45506. }
  45507. if (this._linkRefractionWithTransparency) {
  45508. return this.getScene().environmentTexture;
  45509. }
  45510. return null;
  45511. };
  45512. /**
  45513. * Disposes the resources of the material.
  45514. * @param forceDisposeEffect - Forces the disposal of effects.
  45515. * @param forceDisposeTextures - Forces the disposal of all textures.
  45516. */
  45517. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45518. if (forceDisposeTextures) {
  45519. if (this._albedoTexture) {
  45520. this._albedoTexture.dispose();
  45521. }
  45522. if (this._ambientTexture) {
  45523. this._ambientTexture.dispose();
  45524. }
  45525. if (this._opacityTexture) {
  45526. this._opacityTexture.dispose();
  45527. }
  45528. if (this._reflectionTexture) {
  45529. this._reflectionTexture.dispose();
  45530. }
  45531. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45532. this._environmentBRDFTexture.dispose();
  45533. }
  45534. if (this._emissiveTexture) {
  45535. this._emissiveTexture.dispose();
  45536. }
  45537. if (this._metallicTexture) {
  45538. this._metallicTexture.dispose();
  45539. }
  45540. if (this._reflectivityTexture) {
  45541. this._reflectivityTexture.dispose();
  45542. }
  45543. if (this._bumpTexture) {
  45544. this._bumpTexture.dispose();
  45545. }
  45546. if (this._lightmapTexture) {
  45547. this._lightmapTexture.dispose();
  45548. }
  45549. if (this._refractionTexture) {
  45550. this._refractionTexture.dispose();
  45551. }
  45552. }
  45553. this._renderTargets.dispose();
  45554. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45555. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45556. }
  45557. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45558. };
  45559. /**
  45560. * Stores the reflectivity values based on metallic roughness workflow.
  45561. */
  45562. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45563. __decorate([
  45564. BABYLON.serializeAsImageProcessingConfiguration()
  45565. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45566. __decorate([
  45567. BABYLON.serialize()
  45568. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45569. __decorate([
  45570. BABYLON.serialize()
  45571. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45572. return PBRBaseMaterial;
  45573. }(BABYLON.PushMaterial));
  45574. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45575. })(BABYLON || (BABYLON = {}));
  45576. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45577. var BABYLON;
  45578. (function (BABYLON) {
  45579. /**
  45580. * The Physically based simple base material of BJS.
  45581. *
  45582. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45583. * It is used as the base class for both the specGloss and metalRough conventions.
  45584. */
  45585. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45586. __extends(PBRBaseSimpleMaterial, _super);
  45587. /**
  45588. * Instantiates a new PBRMaterial instance.
  45589. *
  45590. * @param name The material name
  45591. * @param scene The scene the material will be use in.
  45592. */
  45593. function PBRBaseSimpleMaterial(name, scene) {
  45594. var _this = _super.call(this, name, scene) || this;
  45595. /**
  45596. * Number of Simultaneous lights allowed on the material.
  45597. */
  45598. _this.maxSimultaneousLights = 4;
  45599. /**
  45600. * If sets to true, disables all the lights affecting the material.
  45601. */
  45602. _this.disableLighting = false;
  45603. /**
  45604. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45605. */
  45606. _this.invertNormalMapX = false;
  45607. /**
  45608. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45609. */
  45610. _this.invertNormalMapY = false;
  45611. /**
  45612. * Emissivie color used to self-illuminate the model.
  45613. */
  45614. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45615. /**
  45616. * Occlusion Channel Strenght.
  45617. */
  45618. _this.occlusionStrength = 1.0;
  45619. _this.useLightmapAsShadowmap = false;
  45620. _this._useAlphaFromAlbedoTexture = true;
  45621. _this._useAmbientInGrayScale = true;
  45622. return _this;
  45623. }
  45624. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45625. /**
  45626. * Gets the current double sided mode.
  45627. */
  45628. get: function () {
  45629. return this._twoSidedLighting;
  45630. },
  45631. /**
  45632. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45633. */
  45634. set: function (value) {
  45635. if (this._twoSidedLighting === value) {
  45636. return;
  45637. }
  45638. this._twoSidedLighting = value;
  45639. this.backFaceCulling = !value;
  45640. this._markAllSubMeshesAsTexturesDirty();
  45641. },
  45642. enumerable: true,
  45643. configurable: true
  45644. });
  45645. /**
  45646. * Return the active textures of the material.
  45647. */
  45648. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45649. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45650. if (this.environmentTexture) {
  45651. activeTextures.push(this.environmentTexture);
  45652. }
  45653. if (this.normalTexture) {
  45654. activeTextures.push(this.normalTexture);
  45655. }
  45656. if (this.emissiveTexture) {
  45657. activeTextures.push(this.emissiveTexture);
  45658. }
  45659. if (this.occlusionTexture) {
  45660. activeTextures.push(this.occlusionTexture);
  45661. }
  45662. if (this.lightmapTexture) {
  45663. activeTextures.push(this.lightmapTexture);
  45664. }
  45665. return activeTextures;
  45666. };
  45667. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45668. if (_super.prototype.hasTexture.call(this, texture)) {
  45669. return true;
  45670. }
  45671. if (this.lightmapTexture === texture) {
  45672. return true;
  45673. }
  45674. return false;
  45675. };
  45676. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45677. return "PBRBaseSimpleMaterial";
  45678. };
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45682. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45686. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45687. __decorate([
  45688. BABYLON.serializeAsTexture(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45690. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45698. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45699. __decorate([
  45700. BABYLON.serializeAsTexture(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45702. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45703. __decorate([
  45704. BABYLON.serializeAsColor3("emissive"),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45706. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45707. __decorate([
  45708. BABYLON.serializeAsTexture(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45710. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45714. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45715. __decorate([
  45716. BABYLON.serializeAsTexture(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45718. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45722. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45726. __decorate([
  45727. BABYLON.serializeAsTexture(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45729. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45734. return PBRBaseSimpleMaterial;
  45735. }(BABYLON.PBRBaseMaterial));
  45736. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45737. })(BABYLON || (BABYLON = {}));
  45738. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45739. var BABYLON;
  45740. (function (BABYLON) {
  45741. /**
  45742. * The Physically based material of BJS.
  45743. *
  45744. * This offers the main features of a standard PBR material.
  45745. * For more information, please refer to the documentation :
  45746. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45747. */
  45748. var PBRMaterial = /** @class */ (function (_super) {
  45749. __extends(PBRMaterial, _super);
  45750. /**
  45751. * Instantiates a new PBRMaterial instance.
  45752. *
  45753. * @param name The material name
  45754. * @param scene The scene the material will be use in.
  45755. */
  45756. function PBRMaterial(name, scene) {
  45757. var _this = _super.call(this, name, scene) || this;
  45758. /**
  45759. * Intensity of the direct lights e.g. the four lights available in your scene.
  45760. * This impacts both the direct diffuse and specular highlights.
  45761. */
  45762. _this.directIntensity = 1.0;
  45763. /**
  45764. * Intensity of the emissive part of the material.
  45765. * This helps controlling the emissive effect without modifying the emissive color.
  45766. */
  45767. _this.emissiveIntensity = 1.0;
  45768. /**
  45769. * Intensity of the environment e.g. how much the environment will light the object
  45770. * either through harmonics for rough material or through the refelction for shiny ones.
  45771. */
  45772. _this.environmentIntensity = 1.0;
  45773. /**
  45774. * This is a special control allowing the reduction of the specular highlights coming from the
  45775. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45776. */
  45777. _this.specularIntensity = 1.0;
  45778. /**
  45779. * Debug Control allowing disabling the bump map on this material.
  45780. */
  45781. _this.disableBumpMap = false;
  45782. /**
  45783. * AKA Occlusion Texture Intensity in other nomenclature.
  45784. */
  45785. _this.ambientTextureStrength = 1.0;
  45786. /**
  45787. * The color of a material in ambient lighting.
  45788. */
  45789. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45790. /**
  45791. * AKA Diffuse Color in other nomenclature.
  45792. */
  45793. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45794. /**
  45795. * AKA Specular Color in other nomenclature.
  45796. */
  45797. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45798. /**
  45799. * The color reflected from the material.
  45800. */
  45801. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45802. /**
  45803. * The color emitted from the material.
  45804. */
  45805. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45806. /**
  45807. * AKA Glossiness in other nomenclature.
  45808. */
  45809. _this.microSurface = 1.0;
  45810. /**
  45811. * source material index of refraction (IOR)' / 'destination material IOR.
  45812. */
  45813. _this.indexOfRefraction = 0.66;
  45814. /**
  45815. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45816. */
  45817. _this.invertRefractionY = false;
  45818. /**
  45819. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45820. * Materials half opaque for instance using refraction could benefit from this control.
  45821. */
  45822. _this.linkRefractionWithTransparency = false;
  45823. _this.useLightmapAsShadowmap = false;
  45824. /**
  45825. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45826. */
  45827. _this.useAlphaFromAlbedoTexture = false;
  45828. /**
  45829. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45830. */
  45831. _this.forceAlphaTest = false;
  45832. /**
  45833. * Defines the alpha limits in alpha test mode.
  45834. */
  45835. _this.alphaCutOff = 0.4;
  45836. /**
  45837. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45838. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45839. */
  45840. _this.useSpecularOverAlpha = true;
  45841. /**
  45842. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45843. */
  45844. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45845. /**
  45846. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45847. */
  45848. _this.useRoughnessFromMetallicTextureAlpha = true;
  45849. /**
  45850. * Specifies if the metallic texture contains the roughness information in its green channel.
  45851. */
  45852. _this.useRoughnessFromMetallicTextureGreen = false;
  45853. /**
  45854. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45855. */
  45856. _this.useMetallnessFromMetallicTextureBlue = false;
  45857. /**
  45858. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45859. */
  45860. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45861. /**
  45862. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45863. */
  45864. _this.useAmbientInGrayScale = false;
  45865. /**
  45866. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45867. * The material will try to infer what glossiness each pixel should be.
  45868. */
  45869. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45870. /**
  45871. * BJS is using an harcoded light falloff based on a manually sets up range.
  45872. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45873. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45874. */
  45875. _this.usePhysicalLightFalloff = true;
  45876. /**
  45877. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45878. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45879. */
  45880. _this.useRadianceOverAlpha = true;
  45881. /**
  45882. * Allows using an object space normal map (instead of tangent space).
  45883. */
  45884. _this.useObjectSpaceNormalMap = false;
  45885. /**
  45886. * Allows using the bump map in parallax mode.
  45887. */
  45888. _this.useParallax = false;
  45889. /**
  45890. * Allows using the bump map in parallax occlusion mode.
  45891. */
  45892. _this.useParallaxOcclusion = false;
  45893. /**
  45894. * Controls the scale bias of the parallax mode.
  45895. */
  45896. _this.parallaxScaleBias = 0.05;
  45897. /**
  45898. * If sets to true, disables all the lights affecting the material.
  45899. */
  45900. _this.disableLighting = false;
  45901. /**
  45902. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45903. */
  45904. _this.forceIrradianceInFragment = false;
  45905. /**
  45906. * Number of Simultaneous lights allowed on the material.
  45907. */
  45908. _this.maxSimultaneousLights = 4;
  45909. /**
  45910. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45911. */
  45912. _this.invertNormalMapX = false;
  45913. /**
  45914. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45915. */
  45916. _this.invertNormalMapY = false;
  45917. /**
  45918. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45919. */
  45920. _this.twoSidedLighting = false;
  45921. /**
  45922. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45923. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45924. */
  45925. _this.useAlphaFresnel = false;
  45926. /**
  45927. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45928. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45929. */
  45930. _this.useLinearAlphaFresnel = false;
  45931. /**
  45932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45933. * And/Or occlude the blended part.
  45934. */
  45935. _this.environmentBRDFTexture = null;
  45936. /**
  45937. * Force normal to face away from face.
  45938. */
  45939. _this.forceNormalForward = false;
  45940. /**
  45941. * Enables specular anti aliasing in the PBR shader.
  45942. * It will both interacts on the Geometry for analytical and IBL lighting.
  45943. * It also prefilter the roughness map based on the bump values.
  45944. */
  45945. _this.enableSpecularAntiAliasing = false;
  45946. /**
  45947. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45948. * makes the reflect vector face the model (under horizon).
  45949. */
  45950. _this.useHorizonOcclusion = true;
  45951. /**
  45952. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45953. * too much the area relying on ambient texture to define their ambient occlusion.
  45954. */
  45955. _this.useRadianceOcclusion = true;
  45956. /**
  45957. * If set to true, no lighting calculations will be applied.
  45958. */
  45959. _this.unlit = false;
  45960. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45961. return _this;
  45962. }
  45963. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45964. /**
  45965. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45966. */
  45967. get: function () {
  45968. return this._PBRMATERIAL_OPAQUE;
  45969. },
  45970. enumerable: true,
  45971. configurable: true
  45972. });
  45973. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45974. /**
  45975. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45976. */
  45977. get: function () {
  45978. return this._PBRMATERIAL_ALPHATEST;
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45984. /**
  45985. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45986. */
  45987. get: function () {
  45988. return this._PBRMATERIAL_ALPHABLEND;
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45994. /**
  45995. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45996. * They are also discarded below the alpha cutoff threshold to improve performances.
  45997. */
  45998. get: function () {
  45999. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46000. },
  46001. enumerable: true,
  46002. configurable: true
  46003. });
  46004. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46005. /**
  46006. * Gets the image processing configuration used either in this material.
  46007. */
  46008. get: function () {
  46009. return this._imageProcessingConfiguration;
  46010. },
  46011. /**
  46012. * Sets the Default image processing configuration used either in the this material.
  46013. *
  46014. * If sets to null, the scene one is in use.
  46015. */
  46016. set: function (value) {
  46017. this._attachImageProcessingConfiguration(value);
  46018. // Ensure the effect will be rebuilt.
  46019. this._markAllSubMeshesAsTexturesDirty();
  46020. },
  46021. enumerable: true,
  46022. configurable: true
  46023. });
  46024. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46025. /**
  46026. * Gets wether the color curves effect is enabled.
  46027. */
  46028. get: function () {
  46029. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46030. },
  46031. /**
  46032. * Sets wether the color curves effect is enabled.
  46033. */
  46034. set: function (value) {
  46035. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46036. },
  46037. enumerable: true,
  46038. configurable: true
  46039. });
  46040. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46041. /**
  46042. * Gets wether the color grading effect is enabled.
  46043. */
  46044. get: function () {
  46045. return this.imageProcessingConfiguration.colorGradingEnabled;
  46046. },
  46047. /**
  46048. * Gets wether the color grading effect is enabled.
  46049. */
  46050. set: function (value) {
  46051. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46052. },
  46053. enumerable: true,
  46054. configurable: true
  46055. });
  46056. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46057. /**
  46058. * Gets wether tonemapping is enabled or not.
  46059. */
  46060. get: function () {
  46061. return this._imageProcessingConfiguration.toneMappingEnabled;
  46062. },
  46063. /**
  46064. * Sets wether tonemapping is enabled or not
  46065. */
  46066. set: function (value) {
  46067. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46068. },
  46069. enumerable: true,
  46070. configurable: true
  46071. });
  46072. ;
  46073. ;
  46074. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46075. /**
  46076. * The camera exposure used on this material.
  46077. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46078. * This corresponds to a photographic exposure.
  46079. */
  46080. get: function () {
  46081. return this._imageProcessingConfiguration.exposure;
  46082. },
  46083. /**
  46084. * The camera exposure used on this material.
  46085. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46086. * This corresponds to a photographic exposure.
  46087. */
  46088. set: function (value) {
  46089. this._imageProcessingConfiguration.exposure = value;
  46090. },
  46091. enumerable: true,
  46092. configurable: true
  46093. });
  46094. ;
  46095. ;
  46096. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46097. /**
  46098. * Gets The camera contrast used on this material.
  46099. */
  46100. get: function () {
  46101. return this._imageProcessingConfiguration.contrast;
  46102. },
  46103. /**
  46104. * Sets The camera contrast used on this material.
  46105. */
  46106. set: function (value) {
  46107. this._imageProcessingConfiguration.contrast = value;
  46108. },
  46109. enumerable: true,
  46110. configurable: true
  46111. });
  46112. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46113. /**
  46114. * Gets the Color Grading 2D Lookup Texture.
  46115. */
  46116. get: function () {
  46117. return this._imageProcessingConfiguration.colorGradingTexture;
  46118. },
  46119. /**
  46120. * Sets the Color Grading 2D Lookup Texture.
  46121. */
  46122. set: function (value) {
  46123. this._imageProcessingConfiguration.colorGradingTexture = value;
  46124. },
  46125. enumerable: true,
  46126. configurable: true
  46127. });
  46128. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46129. /**
  46130. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46131. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46132. * 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;
  46133. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46134. */
  46135. get: function () {
  46136. return this._imageProcessingConfiguration.colorCurves;
  46137. },
  46138. /**
  46139. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46140. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46141. * 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;
  46142. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46143. */
  46144. set: function (value) {
  46145. this._imageProcessingConfiguration.colorCurves = value;
  46146. },
  46147. enumerable: true,
  46148. configurable: true
  46149. });
  46150. /**
  46151. * Returns the name of this material class.
  46152. */
  46153. PBRMaterial.prototype.getClassName = function () {
  46154. return "PBRMaterial";
  46155. };
  46156. /**
  46157. * Returns an array of the actively used textures.
  46158. * @returns - Array of BaseTextures
  46159. */
  46160. PBRMaterial.prototype.getActiveTextures = function () {
  46161. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46162. if (this._albedoTexture) {
  46163. activeTextures.push(this._albedoTexture);
  46164. }
  46165. if (this._ambientTexture) {
  46166. activeTextures.push(this._ambientTexture);
  46167. }
  46168. if (this._opacityTexture) {
  46169. activeTextures.push(this._opacityTexture);
  46170. }
  46171. if (this._reflectionTexture) {
  46172. activeTextures.push(this._reflectionTexture);
  46173. }
  46174. if (this._emissiveTexture) {
  46175. activeTextures.push(this._emissiveTexture);
  46176. }
  46177. if (this._reflectivityTexture) {
  46178. activeTextures.push(this._reflectivityTexture);
  46179. }
  46180. if (this._metallicTexture) {
  46181. activeTextures.push(this._metallicTexture);
  46182. }
  46183. if (this._microSurfaceTexture) {
  46184. activeTextures.push(this._microSurfaceTexture);
  46185. }
  46186. if (this._bumpTexture) {
  46187. activeTextures.push(this._bumpTexture);
  46188. }
  46189. if (this._lightmapTexture) {
  46190. activeTextures.push(this._lightmapTexture);
  46191. }
  46192. if (this._refractionTexture) {
  46193. activeTextures.push(this._refractionTexture);
  46194. }
  46195. return activeTextures;
  46196. };
  46197. /**
  46198. * Checks to see if a texture is used in the material.
  46199. * @param texture - Base texture to use.
  46200. * @returns - Boolean specifying if a texture is used in the material.
  46201. */
  46202. PBRMaterial.prototype.hasTexture = function (texture) {
  46203. if (_super.prototype.hasTexture.call(this, texture)) {
  46204. return true;
  46205. }
  46206. if (this._albedoTexture === texture) {
  46207. return true;
  46208. }
  46209. if (this._ambientTexture === texture) {
  46210. return true;
  46211. }
  46212. if (this._opacityTexture === texture) {
  46213. return true;
  46214. }
  46215. if (this._reflectionTexture === texture) {
  46216. return true;
  46217. }
  46218. if (this._reflectivityTexture === texture) {
  46219. return true;
  46220. }
  46221. if (this._metallicTexture === texture) {
  46222. return true;
  46223. }
  46224. if (this._microSurfaceTexture === texture) {
  46225. return true;
  46226. }
  46227. if (this._bumpTexture === texture) {
  46228. return true;
  46229. }
  46230. if (this._lightmapTexture === texture) {
  46231. return true;
  46232. }
  46233. if (this._refractionTexture === texture) {
  46234. return true;
  46235. }
  46236. return false;
  46237. };
  46238. /**
  46239. * Makes a duplicate of the current material.
  46240. * @param name - name to use for the new material.
  46241. */
  46242. PBRMaterial.prototype.clone = function (name) {
  46243. var _this = this;
  46244. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46245. clone.id = name;
  46246. clone.name = name;
  46247. return clone;
  46248. };
  46249. /**
  46250. * Serializes this PBR Material.
  46251. * @returns - An object with the serialized material.
  46252. */
  46253. PBRMaterial.prototype.serialize = function () {
  46254. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46255. serializationObject.customType = "BABYLON.PBRMaterial";
  46256. return serializationObject;
  46257. };
  46258. // Statics
  46259. /**
  46260. * Parses a PBR Material from a serialized object.
  46261. * @param source - Serialized object.
  46262. * @param scene - BJS scene instance.
  46263. * @param rootUrl - url for the scene object
  46264. * @returns - PBRMaterial
  46265. */
  46266. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46267. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46268. };
  46269. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46270. /**
  46271. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46272. */
  46273. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46274. /**
  46275. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46276. */
  46277. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46278. /**
  46279. * 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.
  46280. * They are also discarded below the alpha cutoff threshold to improve performances.
  46281. */
  46282. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46283. __decorate([
  46284. BABYLON.serialize(),
  46285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46286. ], PBRMaterial.prototype, "directIntensity", void 0);
  46287. __decorate([
  46288. BABYLON.serialize(),
  46289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46290. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46291. __decorate([
  46292. BABYLON.serialize(),
  46293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46294. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46295. __decorate([
  46296. BABYLON.serialize(),
  46297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46298. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46299. __decorate([
  46300. BABYLON.serialize(),
  46301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46302. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46303. __decorate([
  46304. BABYLON.serializeAsTexture(),
  46305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46306. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46307. __decorate([
  46308. BABYLON.serializeAsTexture(),
  46309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46310. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46311. __decorate([
  46312. BABYLON.serialize(),
  46313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46314. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46315. __decorate([
  46316. BABYLON.serializeAsTexture(),
  46317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46318. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46319. __decorate([
  46320. BABYLON.serializeAsTexture(),
  46321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46322. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46323. __decorate([
  46324. BABYLON.serializeAsTexture(),
  46325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46326. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46327. __decorate([
  46328. BABYLON.serializeAsTexture(),
  46329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46330. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46331. __decorate([
  46332. BABYLON.serializeAsTexture(),
  46333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46334. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46335. __decorate([
  46336. BABYLON.serialize(),
  46337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46338. ], PBRMaterial.prototype, "metallic", void 0);
  46339. __decorate([
  46340. BABYLON.serialize(),
  46341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46342. ], PBRMaterial.prototype, "roughness", void 0);
  46343. __decorate([
  46344. BABYLON.serializeAsTexture(),
  46345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46346. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46347. __decorate([
  46348. BABYLON.serializeAsTexture(),
  46349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46350. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46351. __decorate([
  46352. BABYLON.serializeAsTexture(),
  46353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46354. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46355. __decorate([
  46356. BABYLON.serializeAsTexture(),
  46357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46358. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46359. __decorate([
  46360. BABYLON.serializeAsColor3("ambient"),
  46361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46362. ], PBRMaterial.prototype, "ambientColor", void 0);
  46363. __decorate([
  46364. BABYLON.serializeAsColor3("albedo"),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46366. ], PBRMaterial.prototype, "albedoColor", void 0);
  46367. __decorate([
  46368. BABYLON.serializeAsColor3("reflectivity"),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46371. __decorate([
  46372. BABYLON.serializeAsColor3("reflection"),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46374. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46375. __decorate([
  46376. BABYLON.serializeAsColor3("emissive"),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46378. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46379. __decorate([
  46380. BABYLON.serialize(),
  46381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46382. ], PBRMaterial.prototype, "microSurface", void 0);
  46383. __decorate([
  46384. BABYLON.serialize(),
  46385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46386. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46387. __decorate([
  46388. BABYLON.serialize(),
  46389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46390. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46391. __decorate([
  46392. BABYLON.serialize(),
  46393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46394. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46395. __decorate([
  46396. BABYLON.serialize(),
  46397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46398. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46399. __decorate([
  46400. BABYLON.serialize(),
  46401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46402. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46403. __decorate([
  46404. BABYLON.serialize(),
  46405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46406. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46407. __decorate([
  46408. BABYLON.serialize(),
  46409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46410. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46411. __decorate([
  46412. BABYLON.serialize(),
  46413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46414. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46415. __decorate([
  46416. BABYLON.serialize(),
  46417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46418. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46419. __decorate([
  46420. BABYLON.serialize(),
  46421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46422. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46423. __decorate([
  46424. BABYLON.serialize(),
  46425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46426. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46427. __decorate([
  46428. BABYLON.serialize(),
  46429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46430. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46431. __decorate([
  46432. BABYLON.serialize(),
  46433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46434. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46435. __decorate([
  46436. BABYLON.serialize(),
  46437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46438. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46439. __decorate([
  46440. BABYLON.serialize(),
  46441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46442. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46443. __decorate([
  46444. BABYLON.serialize(),
  46445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46446. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46447. __decorate([
  46448. BABYLON.serialize(),
  46449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46450. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46451. __decorate([
  46452. BABYLON.serialize(),
  46453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46454. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46455. __decorate([
  46456. BABYLON.serialize(),
  46457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46458. ], PBRMaterial.prototype, "useParallax", void 0);
  46459. __decorate([
  46460. BABYLON.serialize(),
  46461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46462. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46463. __decorate([
  46464. BABYLON.serialize(),
  46465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46466. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46467. __decorate([
  46468. BABYLON.serialize(),
  46469. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46470. ], PBRMaterial.prototype, "disableLighting", void 0);
  46471. __decorate([
  46472. BABYLON.serialize(),
  46473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46474. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46475. __decorate([
  46476. BABYLON.serialize(),
  46477. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46478. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46479. __decorate([
  46480. BABYLON.serialize(),
  46481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46482. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46483. __decorate([
  46484. BABYLON.serialize(),
  46485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46486. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46487. __decorate([
  46488. BABYLON.serialize(),
  46489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46490. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46491. __decorate([
  46492. BABYLON.serialize(),
  46493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46494. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46495. __decorate([
  46496. BABYLON.serialize(),
  46497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46498. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46499. __decorate([
  46500. BABYLON.serializeAsTexture(),
  46501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46502. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46503. __decorate([
  46504. BABYLON.serialize(),
  46505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46506. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46507. __decorate([
  46508. BABYLON.serialize(),
  46509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46510. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46511. __decorate([
  46512. BABYLON.serialize(),
  46513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46514. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46515. __decorate([
  46516. BABYLON.serialize(),
  46517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46518. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46519. __decorate([
  46520. BABYLON.serialize(),
  46521. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46522. ], PBRMaterial.prototype, "unlit", void 0);
  46523. return PBRMaterial;
  46524. }(BABYLON.PBRBaseMaterial));
  46525. BABYLON.PBRMaterial = PBRMaterial;
  46526. })(BABYLON || (BABYLON = {}));
  46527. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46528. var BABYLON;
  46529. (function (BABYLON) {
  46530. /**
  46531. * The PBR material of BJS following the metal roughness convention.
  46532. *
  46533. * This fits to the PBR convention in the GLTF definition:
  46534. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46535. */
  46536. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46537. __extends(PBRMetallicRoughnessMaterial, _super);
  46538. /**
  46539. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46540. *
  46541. * @param name The material name
  46542. * @param scene The scene the material will be use in.
  46543. */
  46544. function PBRMetallicRoughnessMaterial(name, scene) {
  46545. var _this = _super.call(this, name, scene) || this;
  46546. _this._useRoughnessFromMetallicTextureAlpha = false;
  46547. _this._useRoughnessFromMetallicTextureGreen = true;
  46548. _this._useMetallnessFromMetallicTextureBlue = true;
  46549. _this.metallic = 1.0;
  46550. _this.roughness = 1.0;
  46551. return _this;
  46552. }
  46553. /**
  46554. * Return the currrent class name of the material.
  46555. */
  46556. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46557. return "PBRMetallicRoughnessMaterial";
  46558. };
  46559. /**
  46560. * Return the active textures of the material.
  46561. */
  46562. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46563. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46564. if (this.baseTexture) {
  46565. activeTextures.push(this.baseTexture);
  46566. }
  46567. if (this.metallicRoughnessTexture) {
  46568. activeTextures.push(this.metallicRoughnessTexture);
  46569. }
  46570. return activeTextures;
  46571. };
  46572. /**
  46573. * Checks to see if a texture is used in the material.
  46574. * @param texture - Base texture to use.
  46575. * @returns - Boolean specifying if a texture is used in the material.
  46576. */
  46577. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46578. if (_super.prototype.hasTexture.call(this, texture)) {
  46579. return true;
  46580. }
  46581. if (this.baseTexture === texture) {
  46582. return true;
  46583. }
  46584. if (this.metallicRoughnessTexture === texture) {
  46585. return true;
  46586. }
  46587. return false;
  46588. };
  46589. /**
  46590. * Makes a duplicate of the current material.
  46591. * @param name - name to use for the new material.
  46592. */
  46593. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46594. var _this = this;
  46595. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46596. clone.id = name;
  46597. clone.name = name;
  46598. return clone;
  46599. };
  46600. /**
  46601. * Serialize the material to a parsable JSON object.
  46602. */
  46603. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46604. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46605. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46606. return serializationObject;
  46607. };
  46608. /**
  46609. * Parses a JSON object correponding to the serialize function.
  46610. */
  46611. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46612. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46613. };
  46614. __decorate([
  46615. BABYLON.serializeAsColor3(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46617. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46618. __decorate([
  46619. BABYLON.serializeAsTexture(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46621. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46622. __decorate([
  46623. BABYLON.serialize(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46626. __decorate([
  46627. BABYLON.serialize(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46630. __decorate([
  46631. BABYLON.serializeAsTexture(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46633. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46634. return PBRMetallicRoughnessMaterial;
  46635. }(BABYLON.PBRBaseSimpleMaterial));
  46636. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46637. })(BABYLON || (BABYLON = {}));
  46638. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46639. var BABYLON;
  46640. (function (BABYLON) {
  46641. /**
  46642. * The PBR material of BJS following the specular glossiness convention.
  46643. *
  46644. * This fits to the PBR convention in the GLTF definition:
  46645. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46646. */
  46647. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46648. __extends(PBRSpecularGlossinessMaterial, _super);
  46649. /**
  46650. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46651. *
  46652. * @param name The material name
  46653. * @param scene The scene the material will be use in.
  46654. */
  46655. function PBRSpecularGlossinessMaterial(name, scene) {
  46656. var _this = _super.call(this, name, scene) || this;
  46657. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46658. return _this;
  46659. }
  46660. /**
  46661. * Return the currrent class name of the material.
  46662. */
  46663. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46664. return "PBRSpecularGlossinessMaterial";
  46665. };
  46666. /**
  46667. * Return the active textures of the material.
  46668. */
  46669. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46670. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46671. if (this.diffuseTexture) {
  46672. activeTextures.push(this.diffuseTexture);
  46673. }
  46674. if (this.specularGlossinessTexture) {
  46675. activeTextures.push(this.specularGlossinessTexture);
  46676. }
  46677. return activeTextures;
  46678. };
  46679. /**
  46680. * Checks to see if a texture is used in the material.
  46681. * @param texture - Base texture to use.
  46682. * @returns - Boolean specifying if a texture is used in the material.
  46683. */
  46684. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46685. if (_super.prototype.hasTexture.call(this, texture)) {
  46686. return true;
  46687. }
  46688. if (this.diffuseTexture === texture) {
  46689. return true;
  46690. }
  46691. if (this.specularGlossinessTexture === texture) {
  46692. return true;
  46693. }
  46694. return false;
  46695. };
  46696. /**
  46697. * Makes a duplicate of the current material.
  46698. * @param name - name to use for the new material.
  46699. */
  46700. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46701. var _this = this;
  46702. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46703. clone.id = name;
  46704. clone.name = name;
  46705. return clone;
  46706. };
  46707. /**
  46708. * Serialize the material to a parsable JSON object.
  46709. */
  46710. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46711. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46712. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46713. return serializationObject;
  46714. };
  46715. /**
  46716. * Parses a JSON object correponding to the serialize function.
  46717. */
  46718. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46719. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46720. };
  46721. __decorate([
  46722. BABYLON.serializeAsColor3("diffuse"),
  46723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46724. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46725. __decorate([
  46726. BABYLON.serializeAsTexture(),
  46727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46728. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46729. __decorate([
  46730. BABYLON.serializeAsColor3("specular"),
  46731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46732. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46733. __decorate([
  46734. BABYLON.serialize(),
  46735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46736. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46737. __decorate([
  46738. BABYLON.serializeAsTexture(),
  46739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46740. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46741. return PBRSpecularGlossinessMaterial;
  46742. }(BABYLON.PBRBaseSimpleMaterial));
  46743. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46744. })(BABYLON || (BABYLON = {}));
  46745. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46746. var BABYLON;
  46747. (function (BABYLON) {
  46748. BABYLON.CameraInputTypes = {};
  46749. var CameraInputsManager = /** @class */ (function () {
  46750. function CameraInputsManager(camera) {
  46751. this.attached = {};
  46752. this.camera = camera;
  46753. this.checkInputs = function () { };
  46754. }
  46755. /**
  46756. * Add an input method to a camera.
  46757. * builtin inputs example: camera.inputs.addGamepad();
  46758. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46759. * @param input camera input method
  46760. */
  46761. CameraInputsManager.prototype.add = function (input) {
  46762. var type = input.getSimpleName();
  46763. if (this.attached[type]) {
  46764. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46765. return;
  46766. }
  46767. this.attached[type] = input;
  46768. input.camera = this.camera;
  46769. //for checkInputs, we are dynamically creating a function
  46770. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46771. if (input.checkInputs) {
  46772. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46773. }
  46774. if (this.attachedElement) {
  46775. input.attachControl(this.attachedElement);
  46776. }
  46777. };
  46778. /**
  46779. * Remove a specific input method from a camera
  46780. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46781. * @param inputToRemove camera input method
  46782. */
  46783. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46784. for (var cam in this.attached) {
  46785. var input = this.attached[cam];
  46786. if (input === inputToRemove) {
  46787. input.detachControl(this.attachedElement);
  46788. input.camera = null;
  46789. delete this.attached[cam];
  46790. this.rebuildInputCheck();
  46791. }
  46792. }
  46793. };
  46794. CameraInputsManager.prototype.removeByType = function (inputType) {
  46795. for (var cam in this.attached) {
  46796. var input = this.attached[cam];
  46797. if (input.getClassName() === inputType) {
  46798. input.detachControl(this.attachedElement);
  46799. input.camera = null;
  46800. delete this.attached[cam];
  46801. this.rebuildInputCheck();
  46802. }
  46803. }
  46804. };
  46805. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46806. var current = this.checkInputs;
  46807. return function () {
  46808. current();
  46809. fn();
  46810. };
  46811. };
  46812. CameraInputsManager.prototype.attachInput = function (input) {
  46813. if (this.attachedElement) {
  46814. input.attachControl(this.attachedElement, this.noPreventDefault);
  46815. }
  46816. };
  46817. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46818. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46819. if (this.attachedElement) {
  46820. return;
  46821. }
  46822. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46823. this.attachedElement = element;
  46824. this.noPreventDefault = noPreventDefault;
  46825. for (var cam in this.attached) {
  46826. this.attached[cam].attachControl(element, noPreventDefault);
  46827. }
  46828. };
  46829. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46830. if (disconnect === void 0) { disconnect = false; }
  46831. if (this.attachedElement !== element) {
  46832. return;
  46833. }
  46834. for (var cam in this.attached) {
  46835. this.attached[cam].detachControl(element);
  46836. if (disconnect) {
  46837. this.attached[cam].camera = null;
  46838. }
  46839. }
  46840. this.attachedElement = null;
  46841. };
  46842. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46843. this.checkInputs = function () { };
  46844. for (var cam in this.attached) {
  46845. var input = this.attached[cam];
  46846. if (input.checkInputs) {
  46847. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46848. }
  46849. }
  46850. };
  46851. /**
  46852. * Remove all attached input methods from a camera
  46853. */
  46854. CameraInputsManager.prototype.clear = function () {
  46855. if (this.attachedElement) {
  46856. this.detachElement(this.attachedElement, true);
  46857. }
  46858. this.attached = {};
  46859. this.attachedElement = null;
  46860. this.checkInputs = function () { };
  46861. };
  46862. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46863. var inputs = {};
  46864. for (var cam in this.attached) {
  46865. var input = this.attached[cam];
  46866. var res = BABYLON.SerializationHelper.Serialize(input);
  46867. inputs[input.getClassName()] = res;
  46868. }
  46869. serializedCamera.inputsmgr = inputs;
  46870. };
  46871. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46872. var parsedInputs = parsedCamera.inputsmgr;
  46873. if (parsedInputs) {
  46874. this.clear();
  46875. for (var n in parsedInputs) {
  46876. var construct = BABYLON.CameraInputTypes[n];
  46877. if (construct) {
  46878. var parsedinput = parsedInputs[n];
  46879. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46880. this.add(input);
  46881. }
  46882. }
  46883. }
  46884. else {
  46885. //2016-03-08 this part is for managing backward compatibility
  46886. for (var n in this.attached) {
  46887. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46888. if (construct) {
  46889. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46890. this.remove(this.attached[n]);
  46891. this.add(input);
  46892. }
  46893. }
  46894. }
  46895. };
  46896. return CameraInputsManager;
  46897. }());
  46898. BABYLON.CameraInputsManager = CameraInputsManager;
  46899. })(BABYLON || (BABYLON = {}));
  46900. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46901. var BABYLON;
  46902. (function (BABYLON) {
  46903. var TargetCamera = /** @class */ (function (_super) {
  46904. __extends(TargetCamera, _super);
  46905. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46906. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46907. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46908. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46909. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46910. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46911. _this.speed = 2.0;
  46912. _this.noRotationConstraint = false;
  46913. _this.lockedTarget = null;
  46914. _this._currentTarget = BABYLON.Vector3.Zero();
  46915. _this._viewMatrix = BABYLON.Matrix.Zero();
  46916. _this._camMatrix = BABYLON.Matrix.Zero();
  46917. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46918. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46919. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46920. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46921. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46922. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46923. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46924. return _this;
  46925. }
  46926. TargetCamera.prototype.getFrontPosition = function (distance) {
  46927. this.getWorldMatrix();
  46928. var direction = this.getTarget().subtract(this.position);
  46929. direction.normalize();
  46930. direction.scaleInPlace(distance);
  46931. return this.globalPosition.add(direction);
  46932. };
  46933. TargetCamera.prototype._getLockedTargetPosition = function () {
  46934. if (!this.lockedTarget) {
  46935. return null;
  46936. }
  46937. if (this.lockedTarget.absolutePosition) {
  46938. this.lockedTarget.computeWorldMatrix();
  46939. }
  46940. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46941. };
  46942. TargetCamera.prototype.storeState = function () {
  46943. this._storedPosition = this.position.clone();
  46944. this._storedRotation = this.rotation.clone();
  46945. if (this.rotationQuaternion) {
  46946. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46947. }
  46948. return _super.prototype.storeState.call(this);
  46949. };
  46950. /**
  46951. * Restored camera state. You must call storeState() first
  46952. */
  46953. TargetCamera.prototype._restoreStateValues = function () {
  46954. if (!_super.prototype._restoreStateValues.call(this)) {
  46955. return false;
  46956. }
  46957. this.position = this._storedPosition.clone();
  46958. this.rotation = this._storedRotation.clone();
  46959. if (this.rotationQuaternion) {
  46960. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46961. }
  46962. this.cameraDirection.copyFromFloats(0, 0, 0);
  46963. this.cameraRotation.copyFromFloats(0, 0);
  46964. return true;
  46965. };
  46966. // Cache
  46967. TargetCamera.prototype._initCache = function () {
  46968. _super.prototype._initCache.call(this);
  46969. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46970. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46971. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46972. };
  46973. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46974. if (!ignoreParentClass) {
  46975. _super.prototype._updateCache.call(this);
  46976. }
  46977. var lockedTargetPosition = this._getLockedTargetPosition();
  46978. if (!lockedTargetPosition) {
  46979. this._cache.lockedTarget = null;
  46980. }
  46981. else {
  46982. if (!this._cache.lockedTarget) {
  46983. this._cache.lockedTarget = lockedTargetPosition.clone();
  46984. }
  46985. else {
  46986. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46987. }
  46988. }
  46989. this._cache.rotation.copyFrom(this.rotation);
  46990. if (this.rotationQuaternion)
  46991. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46992. };
  46993. // Synchronized
  46994. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46995. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46996. return false;
  46997. }
  46998. var lockedTargetPosition = this._getLockedTargetPosition();
  46999. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47000. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47001. };
  47002. // Methods
  47003. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47004. var engine = this.getEngine();
  47005. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47006. };
  47007. // Target
  47008. TargetCamera.prototype.setTarget = function (target) {
  47009. this.upVector.normalize();
  47010. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47011. this._camMatrix.invert();
  47012. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47013. var vDir = target.subtract(this.position);
  47014. if (vDir.x >= 0.0) {
  47015. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47016. }
  47017. else {
  47018. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47019. }
  47020. this.rotation.z = 0;
  47021. if (isNaN(this.rotation.x)) {
  47022. this.rotation.x = 0;
  47023. }
  47024. if (isNaN(this.rotation.y)) {
  47025. this.rotation.y = 0;
  47026. }
  47027. if (isNaN(this.rotation.z)) {
  47028. this.rotation.z = 0;
  47029. }
  47030. if (this.rotationQuaternion) {
  47031. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47032. }
  47033. };
  47034. /**
  47035. * Return the current target position of the camera. This value is expressed in local space.
  47036. */
  47037. TargetCamera.prototype.getTarget = function () {
  47038. return this._currentTarget;
  47039. };
  47040. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47041. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47042. };
  47043. TargetCamera.prototype._updatePosition = function () {
  47044. if (this.parent) {
  47045. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47046. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47047. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47048. return;
  47049. }
  47050. this.position.addInPlace(this.cameraDirection);
  47051. };
  47052. TargetCamera.prototype._checkInputs = function () {
  47053. var needToMove = this._decideIfNeedsToMove();
  47054. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47055. // Move
  47056. if (needToMove) {
  47057. this._updatePosition();
  47058. }
  47059. // Rotate
  47060. if (needToRotate) {
  47061. this.rotation.x += this.cameraRotation.x;
  47062. this.rotation.y += this.cameraRotation.y;
  47063. //rotate, if quaternion is set and rotation was used
  47064. if (this.rotationQuaternion) {
  47065. var len = this.rotation.lengthSquared();
  47066. if (len) {
  47067. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47068. }
  47069. }
  47070. if (!this.noRotationConstraint) {
  47071. var limit = (Math.PI / 2) * 0.95;
  47072. if (this.rotation.x > limit)
  47073. this.rotation.x = limit;
  47074. if (this.rotation.x < -limit)
  47075. this.rotation.x = -limit;
  47076. }
  47077. }
  47078. // Inertia
  47079. if (needToMove) {
  47080. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47081. this.cameraDirection.x = 0;
  47082. }
  47083. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47084. this.cameraDirection.y = 0;
  47085. }
  47086. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47087. this.cameraDirection.z = 0;
  47088. }
  47089. this.cameraDirection.scaleInPlace(this.inertia);
  47090. }
  47091. if (needToRotate) {
  47092. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47093. this.cameraRotation.x = 0;
  47094. }
  47095. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47096. this.cameraRotation.y = 0;
  47097. }
  47098. this.cameraRotation.scaleInPlace(this.inertia);
  47099. }
  47100. _super.prototype._checkInputs.call(this);
  47101. };
  47102. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47103. if (this.rotationQuaternion) {
  47104. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47105. }
  47106. else {
  47107. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47108. }
  47109. //update the up vector!
  47110. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47111. };
  47112. TargetCamera.prototype._getViewMatrix = function () {
  47113. if (this.lockedTarget) {
  47114. this.setTarget(this._getLockedTargetPosition());
  47115. }
  47116. // Compute
  47117. this._updateCameraRotationMatrix();
  47118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47119. // Computing target and final matrix
  47120. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47121. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47122. return this._viewMatrix;
  47123. };
  47124. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47125. if (this.parent) {
  47126. var parentWorldMatrix = this.parent.getWorldMatrix();
  47127. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47128. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47129. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47130. this._markSyncedWithParent();
  47131. }
  47132. else {
  47133. this._globalPosition.copyFrom(this.position);
  47134. this._globalCurrentTarget.copyFrom(target);
  47135. this._globalCurrentUpVector.copyFrom(up);
  47136. }
  47137. if (this.getScene().useRightHandedSystem) {
  47138. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47139. }
  47140. else {
  47141. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47142. }
  47143. };
  47144. /**
  47145. * @override
  47146. * Override Camera.createRigCamera
  47147. */
  47148. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47149. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47150. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47151. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47152. if (!this.rotationQuaternion) {
  47153. this.rotationQuaternion = new BABYLON.Quaternion();
  47154. }
  47155. rigCamera._cameraRigParams = {};
  47156. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47157. }
  47158. return rigCamera;
  47159. }
  47160. return null;
  47161. };
  47162. /**
  47163. * @override
  47164. * Override Camera._updateRigCameras
  47165. */
  47166. TargetCamera.prototype._updateRigCameras = function () {
  47167. var camLeft = this._rigCameras[0];
  47168. var camRight = this._rigCameras[1];
  47169. switch (this.cameraRigMode) {
  47170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47174. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47175. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47176. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47177. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47178. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47179. camLeft.setTarget(this.getTarget());
  47180. camRight.setTarget(this.getTarget());
  47181. break;
  47182. case BABYLON.Camera.RIG_MODE_VR:
  47183. if (camLeft.rotationQuaternion) {
  47184. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47185. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47186. }
  47187. else {
  47188. camLeft.rotation.copyFrom(this.rotation);
  47189. camRight.rotation.copyFrom(this.rotation);
  47190. }
  47191. camLeft.position.copyFrom(this.position);
  47192. camRight.position.copyFrom(this.position);
  47193. break;
  47194. }
  47195. _super.prototype._updateRigCameras.call(this);
  47196. };
  47197. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47198. if (!this._rigCamTransformMatrix) {
  47199. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47200. }
  47201. var target = this.getTarget();
  47202. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47203. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47204. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47205. };
  47206. TargetCamera.prototype.getClassName = function () {
  47207. return "TargetCamera";
  47208. };
  47209. __decorate([
  47210. BABYLON.serializeAsVector3()
  47211. ], TargetCamera.prototype, "rotation", void 0);
  47212. __decorate([
  47213. BABYLON.serialize()
  47214. ], TargetCamera.prototype, "speed", void 0);
  47215. __decorate([
  47216. BABYLON.serializeAsMeshReference("lockedTargetId")
  47217. ], TargetCamera.prototype, "lockedTarget", void 0);
  47218. return TargetCamera;
  47219. }(BABYLON.Camera));
  47220. BABYLON.TargetCamera = TargetCamera;
  47221. })(BABYLON || (BABYLON = {}));
  47222. //# sourceMappingURL=babylon.targetCamera.js.map
  47223. var BABYLON;
  47224. (function (BABYLON) {
  47225. var FreeCameraMouseInput = /** @class */ (function () {
  47226. function FreeCameraMouseInput(touchEnabled) {
  47227. if (touchEnabled === void 0) { touchEnabled = true; }
  47228. this.touchEnabled = touchEnabled;
  47229. this.buttons = [0, 1, 2];
  47230. this.angularSensibility = 2000.0;
  47231. this.previousPosition = null;
  47232. }
  47233. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47234. var _this = this;
  47235. var engine = this.camera.getEngine();
  47236. if (!this._pointerInput) {
  47237. this._pointerInput = function (p, s) {
  47238. var evt = p.event;
  47239. if (engine.isInVRExclusivePointerMode) {
  47240. return;
  47241. }
  47242. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47243. return;
  47244. }
  47245. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47246. return;
  47247. }
  47248. var srcElement = (evt.srcElement || evt.target);
  47249. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47250. try {
  47251. srcElement.setPointerCapture(evt.pointerId);
  47252. }
  47253. catch (e) {
  47254. //Nothing to do with the error. Execution will continue.
  47255. }
  47256. _this.previousPosition = {
  47257. x: evt.clientX,
  47258. y: evt.clientY
  47259. };
  47260. if (!noPreventDefault) {
  47261. evt.preventDefault();
  47262. element.focus();
  47263. }
  47264. }
  47265. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47266. try {
  47267. srcElement.releasePointerCapture(evt.pointerId);
  47268. }
  47269. catch (e) {
  47270. //Nothing to do with the error.
  47271. }
  47272. _this.previousPosition = null;
  47273. if (!noPreventDefault) {
  47274. evt.preventDefault();
  47275. }
  47276. }
  47277. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47278. if (!_this.previousPosition || engine.isPointerLock) {
  47279. return;
  47280. }
  47281. var offsetX = evt.clientX - _this.previousPosition.x;
  47282. if (_this.camera.getScene().useRightHandedSystem)
  47283. offsetX *= -1;
  47284. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47285. offsetX *= -1;
  47286. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47287. var offsetY = evt.clientY - _this.previousPosition.y;
  47288. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47289. _this.previousPosition = {
  47290. x: evt.clientX,
  47291. y: evt.clientY
  47292. };
  47293. if (!noPreventDefault) {
  47294. evt.preventDefault();
  47295. }
  47296. }
  47297. };
  47298. }
  47299. this._onMouseMove = function (evt) {
  47300. if (!engine.isPointerLock) {
  47301. return;
  47302. }
  47303. if (engine.isInVRExclusivePointerMode) {
  47304. return;
  47305. }
  47306. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47307. if (_this.camera.getScene().useRightHandedSystem)
  47308. offsetX *= -1;
  47309. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47310. offsetX *= -1;
  47311. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47312. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47313. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47314. _this.previousPosition = null;
  47315. if (!noPreventDefault) {
  47316. evt.preventDefault();
  47317. }
  47318. };
  47319. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47320. element.addEventListener("mousemove", this._onMouseMove, false);
  47321. };
  47322. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47323. if (this._observer && element) {
  47324. this.camera.getScene().onPointerObservable.remove(this._observer);
  47325. if (this._onMouseMove) {
  47326. element.removeEventListener("mousemove", this._onMouseMove);
  47327. }
  47328. this._observer = null;
  47329. this._onMouseMove = null;
  47330. this.previousPosition = null;
  47331. }
  47332. };
  47333. FreeCameraMouseInput.prototype.getClassName = function () {
  47334. return "FreeCameraMouseInput";
  47335. };
  47336. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47337. return "mouse";
  47338. };
  47339. __decorate([
  47340. BABYLON.serialize()
  47341. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47342. __decorate([
  47343. BABYLON.serialize()
  47344. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47345. return FreeCameraMouseInput;
  47346. }());
  47347. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47348. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47349. })(BABYLON || (BABYLON = {}));
  47350. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47351. var BABYLON;
  47352. (function (BABYLON) {
  47353. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47354. function FreeCameraKeyboardMoveInput() {
  47355. this._keys = new Array();
  47356. this.keysUp = [38];
  47357. this.keysDown = [40];
  47358. this.keysLeft = [37];
  47359. this.keysRight = [39];
  47360. }
  47361. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47362. var _this = this;
  47363. if (this._onCanvasBlurObserver) {
  47364. return;
  47365. }
  47366. this._scene = this.camera.getScene();
  47367. this._engine = this._scene.getEngine();
  47368. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47369. _this._keys = [];
  47370. });
  47371. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47372. var evt = info.event;
  47373. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47374. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47375. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47376. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47377. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47378. var index = _this._keys.indexOf(evt.keyCode);
  47379. if (index === -1) {
  47380. _this._keys.push(evt.keyCode);
  47381. }
  47382. if (!noPreventDefault) {
  47383. evt.preventDefault();
  47384. }
  47385. }
  47386. }
  47387. else {
  47388. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47389. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47390. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47391. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47392. var index = _this._keys.indexOf(evt.keyCode);
  47393. if (index >= 0) {
  47394. _this._keys.splice(index, 1);
  47395. }
  47396. if (!noPreventDefault) {
  47397. evt.preventDefault();
  47398. }
  47399. }
  47400. }
  47401. });
  47402. };
  47403. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47404. if (this._scene) {
  47405. if (this._onKeyboardObserver) {
  47406. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47407. }
  47408. if (this._onCanvasBlurObserver) {
  47409. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47410. }
  47411. this._onKeyboardObserver = null;
  47412. this._onCanvasBlurObserver = null;
  47413. }
  47414. this._keys = [];
  47415. };
  47416. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47417. if (this._onKeyboardObserver) {
  47418. var camera = this.camera;
  47419. // Keyboard
  47420. for (var index = 0; index < this._keys.length; index++) {
  47421. var keyCode = this._keys[index];
  47422. var speed = camera._computeLocalCameraSpeed();
  47423. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47424. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47425. }
  47426. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47427. camera._localDirection.copyFromFloats(0, 0, speed);
  47428. }
  47429. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47430. camera._localDirection.copyFromFloats(speed, 0, 0);
  47431. }
  47432. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47433. camera._localDirection.copyFromFloats(0, 0, -speed);
  47434. }
  47435. if (camera.getScene().useRightHandedSystem) {
  47436. camera._localDirection.z *= -1;
  47437. }
  47438. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47439. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47440. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47441. }
  47442. }
  47443. };
  47444. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47445. return "FreeCameraKeyboardMoveInput";
  47446. };
  47447. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47448. this._keys = [];
  47449. };
  47450. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47451. return "keyboard";
  47452. };
  47453. __decorate([
  47454. BABYLON.serialize()
  47455. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47456. __decorate([
  47457. BABYLON.serialize()
  47458. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47459. __decorate([
  47460. BABYLON.serialize()
  47461. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47462. __decorate([
  47463. BABYLON.serialize()
  47464. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47465. return FreeCameraKeyboardMoveInput;
  47466. }());
  47467. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47468. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47469. })(BABYLON || (BABYLON = {}));
  47470. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47471. var BABYLON;
  47472. (function (BABYLON) {
  47473. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47474. __extends(FreeCameraInputsManager, _super);
  47475. function FreeCameraInputsManager(camera) {
  47476. return _super.call(this, camera) || this;
  47477. }
  47478. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47479. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47480. return this;
  47481. };
  47482. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47483. if (touchEnabled === void 0) { touchEnabled = true; }
  47484. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47485. return this;
  47486. };
  47487. FreeCameraInputsManager.prototype.addGamepad = function () {
  47488. this.add(new BABYLON.FreeCameraGamepadInput());
  47489. return this;
  47490. };
  47491. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47492. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47493. return this;
  47494. };
  47495. FreeCameraInputsManager.prototype.addTouch = function () {
  47496. this.add(new BABYLON.FreeCameraTouchInput());
  47497. return this;
  47498. };
  47499. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47500. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47501. return this;
  47502. };
  47503. return FreeCameraInputsManager;
  47504. }(BABYLON.CameraInputsManager));
  47505. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47506. })(BABYLON || (BABYLON = {}));
  47507. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47508. var BABYLON;
  47509. (function (BABYLON) {
  47510. var FreeCamera = /** @class */ (function (_super) {
  47511. __extends(FreeCamera, _super);
  47512. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47513. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47514. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47515. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47516. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47517. _this.checkCollisions = false;
  47518. _this.applyGravity = false;
  47519. _this._needMoveForGravity = false;
  47520. _this._oldPosition = BABYLON.Vector3.Zero();
  47521. _this._diffPosition = BABYLON.Vector3.Zero();
  47522. _this._newPosition = BABYLON.Vector3.Zero();
  47523. // Collisions
  47524. _this._collisionMask = -1;
  47525. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47526. if (collidedMesh === void 0) { collidedMesh = null; }
  47527. //TODO move this to the collision coordinator!
  47528. if (_this.getScene().workerCollisions)
  47529. newPosition.multiplyInPlace(_this._collider._radius);
  47530. var updatePosition = function (newPos) {
  47531. _this._newPosition.copyFrom(newPos);
  47532. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47533. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47534. _this.position.addInPlace(_this._diffPosition);
  47535. if (_this.onCollide && collidedMesh) {
  47536. _this.onCollide(collidedMesh);
  47537. }
  47538. }
  47539. };
  47540. updatePosition(newPosition);
  47541. };
  47542. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47543. _this.inputs.addKeyboard().addMouse();
  47544. return _this;
  47545. }
  47546. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47547. //-- begin properties for backward compatibility for inputs
  47548. /**
  47549. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47550. * Higher values reduce sensitivity.
  47551. */
  47552. get: function () {
  47553. var mouse = this.inputs.attached["mouse"];
  47554. if (mouse)
  47555. return mouse.angularSensibility;
  47556. return 0;
  47557. },
  47558. /**
  47559. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47560. * Higher values reduce sensitivity.
  47561. */
  47562. set: function (value) {
  47563. var mouse = this.inputs.attached["mouse"];
  47564. if (mouse)
  47565. mouse.angularSensibility = value;
  47566. },
  47567. enumerable: true,
  47568. configurable: true
  47569. });
  47570. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47571. get: function () {
  47572. var keyboard = this.inputs.attached["keyboard"];
  47573. if (keyboard)
  47574. return keyboard.keysUp;
  47575. return [];
  47576. },
  47577. set: function (value) {
  47578. var keyboard = this.inputs.attached["keyboard"];
  47579. if (keyboard)
  47580. keyboard.keysUp = value;
  47581. },
  47582. enumerable: true,
  47583. configurable: true
  47584. });
  47585. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47586. get: function () {
  47587. var keyboard = this.inputs.attached["keyboard"];
  47588. if (keyboard)
  47589. return keyboard.keysDown;
  47590. return [];
  47591. },
  47592. set: function (value) {
  47593. var keyboard = this.inputs.attached["keyboard"];
  47594. if (keyboard)
  47595. keyboard.keysDown = value;
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47601. get: function () {
  47602. var keyboard = this.inputs.attached["keyboard"];
  47603. if (keyboard)
  47604. return keyboard.keysLeft;
  47605. return [];
  47606. },
  47607. set: function (value) {
  47608. var keyboard = this.inputs.attached["keyboard"];
  47609. if (keyboard)
  47610. keyboard.keysLeft = value;
  47611. },
  47612. enumerable: true,
  47613. configurable: true
  47614. });
  47615. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47616. get: function () {
  47617. var keyboard = this.inputs.attached["keyboard"];
  47618. if (keyboard)
  47619. return keyboard.keysRight;
  47620. return [];
  47621. },
  47622. set: function (value) {
  47623. var keyboard = this.inputs.attached["keyboard"];
  47624. if (keyboard)
  47625. keyboard.keysRight = value;
  47626. },
  47627. enumerable: true,
  47628. configurable: true
  47629. });
  47630. // Controls
  47631. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47632. this.inputs.attachElement(element, noPreventDefault);
  47633. };
  47634. FreeCamera.prototype.detachControl = function (element) {
  47635. this.inputs.detachElement(element);
  47636. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47637. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47638. };
  47639. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47640. get: function () {
  47641. return this._collisionMask;
  47642. },
  47643. set: function (mask) {
  47644. this._collisionMask = !isNaN(mask) ? mask : -1;
  47645. },
  47646. enumerable: true,
  47647. configurable: true
  47648. });
  47649. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47650. var globalPosition;
  47651. if (this.parent) {
  47652. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47653. }
  47654. else {
  47655. globalPosition = this.position;
  47656. }
  47657. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47658. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47659. if (!this._collider) {
  47660. this._collider = new BABYLON.Collider();
  47661. }
  47662. this._collider._radius = this.ellipsoid;
  47663. this._collider.collisionMask = this._collisionMask;
  47664. //no need for clone, as long as gravity is not on.
  47665. var actualDisplacement = displacement;
  47666. //add gravity to the direction to prevent the dual-collision checking
  47667. if (this.applyGravity) {
  47668. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47669. actualDisplacement = displacement.add(this.getScene().gravity);
  47670. }
  47671. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47672. };
  47673. FreeCamera.prototype._checkInputs = function () {
  47674. if (!this._localDirection) {
  47675. this._localDirection = BABYLON.Vector3.Zero();
  47676. this._transformedDirection = BABYLON.Vector3.Zero();
  47677. }
  47678. this.inputs.checkInputs();
  47679. _super.prototype._checkInputs.call(this);
  47680. };
  47681. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47682. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47683. };
  47684. FreeCamera.prototype._updatePosition = function () {
  47685. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47686. this._collideWithWorld(this.cameraDirection);
  47687. }
  47688. else {
  47689. _super.prototype._updatePosition.call(this);
  47690. }
  47691. };
  47692. FreeCamera.prototype.dispose = function () {
  47693. this.inputs.clear();
  47694. _super.prototype.dispose.call(this);
  47695. };
  47696. FreeCamera.prototype.getClassName = function () {
  47697. return "FreeCamera";
  47698. };
  47699. __decorate([
  47700. BABYLON.serializeAsVector3()
  47701. ], FreeCamera.prototype, "ellipsoid", void 0);
  47702. __decorate([
  47703. BABYLON.serializeAsVector3()
  47704. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47705. __decorate([
  47706. BABYLON.serialize()
  47707. ], FreeCamera.prototype, "checkCollisions", void 0);
  47708. __decorate([
  47709. BABYLON.serialize()
  47710. ], FreeCamera.prototype, "applyGravity", void 0);
  47711. return FreeCamera;
  47712. }(BABYLON.TargetCamera));
  47713. BABYLON.FreeCamera = FreeCamera;
  47714. })(BABYLON || (BABYLON = {}));
  47715. //# sourceMappingURL=babylon.freeCamera.js.map
  47716. var BABYLON;
  47717. (function (BABYLON) {
  47718. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47719. function ArcRotateCameraKeyboardMoveInput() {
  47720. this._keys = new Array();
  47721. this.keysUp = [38];
  47722. this.keysDown = [40];
  47723. this.keysLeft = [37];
  47724. this.keysRight = [39];
  47725. this.keysReset = [220];
  47726. this.panningSensibility = 50.0;
  47727. this.zoomingSensibility = 25.0;
  47728. this.useAltToZoom = true;
  47729. }
  47730. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47731. var _this = this;
  47732. if (this._onCanvasBlurObserver) {
  47733. return;
  47734. }
  47735. this._scene = this.camera.getScene();
  47736. this._engine = this._scene.getEngine();
  47737. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47738. _this._keys = [];
  47739. });
  47740. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47741. var evt = info.event;
  47742. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47743. _this._ctrlPressed = evt.ctrlKey;
  47744. _this._altPressed = evt.altKey;
  47745. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47746. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47747. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47748. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47749. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47750. var index = _this._keys.indexOf(evt.keyCode);
  47751. if (index === -1) {
  47752. _this._keys.push(evt.keyCode);
  47753. }
  47754. if (evt.preventDefault) {
  47755. if (!noPreventDefault) {
  47756. evt.preventDefault();
  47757. }
  47758. }
  47759. }
  47760. }
  47761. else {
  47762. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47763. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47764. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47765. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47766. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47767. var index = _this._keys.indexOf(evt.keyCode);
  47768. if (index >= 0) {
  47769. _this._keys.splice(index, 1);
  47770. }
  47771. if (evt.preventDefault) {
  47772. if (!noPreventDefault) {
  47773. evt.preventDefault();
  47774. }
  47775. }
  47776. }
  47777. }
  47778. });
  47779. };
  47780. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47781. if (this._scene) {
  47782. if (this._onKeyboardObserver) {
  47783. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47784. }
  47785. if (this._onCanvasBlurObserver) {
  47786. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47787. }
  47788. this._onKeyboardObserver = null;
  47789. this._onCanvasBlurObserver = null;
  47790. }
  47791. this._keys = [];
  47792. };
  47793. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47794. if (this._onKeyboardObserver) {
  47795. var camera = this.camera;
  47796. for (var index = 0; index < this._keys.length; index++) {
  47797. var keyCode = this._keys[index];
  47798. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47799. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47800. camera.inertialPanningX -= 1 / this.panningSensibility;
  47801. }
  47802. else {
  47803. camera.inertialAlphaOffset -= 0.01;
  47804. }
  47805. }
  47806. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47807. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47808. camera.inertialPanningY += 1 / this.panningSensibility;
  47809. }
  47810. else if (this._altPressed && this.useAltToZoom) {
  47811. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47812. }
  47813. else {
  47814. camera.inertialBetaOffset -= 0.01;
  47815. }
  47816. }
  47817. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47818. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47819. camera.inertialPanningX += 1 / this.panningSensibility;
  47820. }
  47821. else {
  47822. camera.inertialAlphaOffset += 0.01;
  47823. }
  47824. }
  47825. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47826. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47827. camera.inertialPanningY -= 1 / this.panningSensibility;
  47828. }
  47829. else if (this._altPressed && this.useAltToZoom) {
  47830. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47831. }
  47832. else {
  47833. camera.inertialBetaOffset += 0.01;
  47834. }
  47835. }
  47836. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47837. camera.restoreState();
  47838. }
  47839. }
  47840. }
  47841. };
  47842. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47843. return "ArcRotateCameraKeyboardMoveInput";
  47844. };
  47845. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47846. return "keyboard";
  47847. };
  47848. __decorate([
  47849. BABYLON.serialize()
  47850. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47851. __decorate([
  47852. BABYLON.serialize()
  47853. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47854. __decorate([
  47855. BABYLON.serialize()
  47856. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47857. __decorate([
  47858. BABYLON.serialize()
  47859. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47860. __decorate([
  47861. BABYLON.serialize()
  47862. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47863. __decorate([
  47864. BABYLON.serialize()
  47865. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47866. __decorate([
  47867. BABYLON.serialize()
  47868. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47869. __decorate([
  47870. BABYLON.serialize()
  47871. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47872. return ArcRotateCameraKeyboardMoveInput;
  47873. }());
  47874. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47875. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47876. })(BABYLON || (BABYLON = {}));
  47877. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47878. var BABYLON;
  47879. (function (BABYLON) {
  47880. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47881. function ArcRotateCameraMouseWheelInput() {
  47882. this.wheelPrecision = 3.0;
  47883. /**
  47884. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47885. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47886. */
  47887. this.wheelDeltaPercentage = 0;
  47888. }
  47889. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47890. var _this = this;
  47891. this._wheel = function (p, s) {
  47892. //sanity check - this should be a PointerWheel event.
  47893. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47894. return;
  47895. var event = p.event;
  47896. var delta = 0;
  47897. if (event.wheelDelta) {
  47898. if (_this.wheelDeltaPercentage) {
  47899. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47900. if (event.wheelDelta > 0) {
  47901. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47902. }
  47903. else {
  47904. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47905. }
  47906. }
  47907. else {
  47908. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47909. }
  47910. }
  47911. else if (event.detail) {
  47912. delta = -event.detail / _this.wheelPrecision;
  47913. }
  47914. if (delta)
  47915. _this.camera.inertialRadiusOffset += delta;
  47916. if (event.preventDefault) {
  47917. if (!noPreventDefault) {
  47918. event.preventDefault();
  47919. }
  47920. }
  47921. };
  47922. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47923. };
  47924. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47925. if (this._observer && element) {
  47926. this.camera.getScene().onPointerObservable.remove(this._observer);
  47927. this._observer = null;
  47928. this._wheel = null;
  47929. }
  47930. };
  47931. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47932. return "ArcRotateCameraMouseWheelInput";
  47933. };
  47934. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47935. return "mousewheel";
  47936. };
  47937. __decorate([
  47938. BABYLON.serialize()
  47939. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47940. __decorate([
  47941. BABYLON.serialize()
  47942. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47943. return ArcRotateCameraMouseWheelInput;
  47944. }());
  47945. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47946. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47947. })(BABYLON || (BABYLON = {}));
  47948. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47949. var BABYLON;
  47950. (function (BABYLON) {
  47951. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47952. function ArcRotateCameraPointersInput() {
  47953. this.buttons = [0, 1, 2];
  47954. this.angularSensibilityX = 1000.0;
  47955. this.angularSensibilityY = 1000.0;
  47956. this.pinchPrecision = 12.0;
  47957. /**
  47958. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47959. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47960. */
  47961. this.pinchDeltaPercentage = 0;
  47962. this.panningSensibility = 1000.0;
  47963. this.multiTouchPanning = true;
  47964. this.multiTouchPanAndZoom = true;
  47965. this._isPanClick = false;
  47966. this.pinchInwards = true;
  47967. }
  47968. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47969. var _this = this;
  47970. var engine = this.camera.getEngine();
  47971. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47972. var pointA = null;
  47973. var pointB = null;
  47974. var previousPinchSquaredDistance = 0;
  47975. var initialDistance = 0;
  47976. var twoFingerActivityCount = 0;
  47977. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47978. this._pointerInput = function (p, s) {
  47979. var evt = p.event;
  47980. var isTouch = p.event.pointerType === "touch";
  47981. if (engine.isInVRExclusivePointerMode) {
  47982. return;
  47983. }
  47984. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47985. return;
  47986. }
  47987. var srcElement = (evt.srcElement || evt.target);
  47988. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47989. try {
  47990. srcElement.setPointerCapture(evt.pointerId);
  47991. }
  47992. catch (e) {
  47993. //Nothing to do with the error. Execution will continue.
  47994. }
  47995. // Manage panning with pan button click
  47996. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47997. // manage pointers
  47998. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47999. if (pointA === null) {
  48000. pointA = cacheSoloPointer;
  48001. }
  48002. else if (pointB === null) {
  48003. pointB = cacheSoloPointer;
  48004. }
  48005. if (!noPreventDefault) {
  48006. evt.preventDefault();
  48007. element.focus();
  48008. }
  48009. }
  48010. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48011. _this.camera.restoreState();
  48012. }
  48013. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48014. try {
  48015. srcElement.releasePointerCapture(evt.pointerId);
  48016. }
  48017. catch (e) {
  48018. //Nothing to do with the error.
  48019. }
  48020. cacheSoloPointer = null;
  48021. previousPinchSquaredDistance = 0;
  48022. previousMultiTouchPanPosition.isPaning = false;
  48023. previousMultiTouchPanPosition.isPinching = false;
  48024. twoFingerActivityCount = 0;
  48025. initialDistance = 0;
  48026. if (!isTouch) {
  48027. pointB = null; // Mouse and pen are mono pointer
  48028. }
  48029. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48030. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48031. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48032. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48033. if (engine._badOS) {
  48034. pointA = pointB = null;
  48035. }
  48036. else {
  48037. //only remove the impacted pointer in case of multitouch allowing on most
  48038. //platforms switching from rotate to zoom and pan seamlessly.
  48039. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48040. pointA = pointB;
  48041. pointB = null;
  48042. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48043. }
  48044. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48045. pointB = null;
  48046. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48047. }
  48048. else {
  48049. pointA = pointB = null;
  48050. }
  48051. }
  48052. if (!noPreventDefault) {
  48053. evt.preventDefault();
  48054. }
  48055. }
  48056. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48057. if (!noPreventDefault) {
  48058. evt.preventDefault();
  48059. }
  48060. // One button down
  48061. if (pointA && pointB === null && cacheSoloPointer) {
  48062. if (_this.panningSensibility !== 0 &&
  48063. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48064. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48065. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48066. }
  48067. else {
  48068. var offsetX = evt.clientX - cacheSoloPointer.x;
  48069. var offsetY = evt.clientY - cacheSoloPointer.y;
  48070. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48071. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48072. }
  48073. cacheSoloPointer.x = evt.clientX;
  48074. cacheSoloPointer.y = evt.clientY;
  48075. }
  48076. // Two buttons down: pinch/pan
  48077. else if (pointA && pointB) {
  48078. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48079. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48080. ed.x = evt.clientX;
  48081. ed.y = evt.clientY;
  48082. var direction = _this.pinchInwards ? 1 : -1;
  48083. var distX = pointA.x - pointB.x;
  48084. var distY = pointA.y - pointB.y;
  48085. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48086. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48087. if (previousPinchSquaredDistance === 0) {
  48088. initialDistance = pinchDistance;
  48089. previousPinchSquaredDistance = pinchSquaredDistance;
  48090. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48091. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48092. return;
  48093. }
  48094. if (_this.multiTouchPanAndZoom) {
  48095. if (_this.pinchDeltaPercentage) {
  48096. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48097. }
  48098. else {
  48099. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48100. (_this.pinchPrecision *
  48101. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48102. direction);
  48103. }
  48104. if (_this.panningSensibility !== 0) {
  48105. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48106. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48107. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48108. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48109. previousMultiTouchPanPosition.x = pointersCenterX;
  48110. previousMultiTouchPanPosition.y = pointersCenterY;
  48111. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48112. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48113. }
  48114. }
  48115. else {
  48116. twoFingerActivityCount++;
  48117. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48118. if (_this.pinchDeltaPercentage) {
  48119. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48120. }
  48121. else {
  48122. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48123. (_this.pinchPrecision *
  48124. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48125. direction);
  48126. }
  48127. previousMultiTouchPanPosition.isPaning = false;
  48128. previousMultiTouchPanPosition.isPinching = true;
  48129. }
  48130. else {
  48131. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48132. if (!previousMultiTouchPanPosition.isPaning) {
  48133. previousMultiTouchPanPosition.isPaning = true;
  48134. previousMultiTouchPanPosition.isPinching = false;
  48135. previousMultiTouchPanPosition.x = ed.x;
  48136. previousMultiTouchPanPosition.y = ed.y;
  48137. return;
  48138. }
  48139. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48140. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48141. }
  48142. }
  48143. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48144. previousMultiTouchPanPosition.x = ed.x;
  48145. previousMultiTouchPanPosition.y = ed.y;
  48146. }
  48147. }
  48148. previousPinchSquaredDistance = pinchSquaredDistance;
  48149. }
  48150. }
  48151. };
  48152. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48153. this._onContextMenu = function (evt) {
  48154. evt.preventDefault();
  48155. };
  48156. if (!this.camera._useCtrlForPanning) {
  48157. element.addEventListener("contextmenu", this._onContextMenu, false);
  48158. }
  48159. this._onLostFocus = function () {
  48160. //this._keys = [];
  48161. pointA = pointB = null;
  48162. previousPinchSquaredDistance = 0;
  48163. previousMultiTouchPanPosition.isPaning = false;
  48164. previousMultiTouchPanPosition.isPinching = false;
  48165. twoFingerActivityCount = 0;
  48166. cacheSoloPointer = null;
  48167. initialDistance = 0;
  48168. };
  48169. this._onMouseMove = function (evt) {
  48170. if (!engine.isPointerLock) {
  48171. return;
  48172. }
  48173. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48174. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48175. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48176. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48177. if (!noPreventDefault) {
  48178. evt.preventDefault();
  48179. }
  48180. };
  48181. this._onGestureStart = function (e) {
  48182. if (window.MSGesture === undefined) {
  48183. return;
  48184. }
  48185. if (!_this._MSGestureHandler) {
  48186. _this._MSGestureHandler = new MSGesture();
  48187. _this._MSGestureHandler.target = element;
  48188. }
  48189. _this._MSGestureHandler.addPointer(e.pointerId);
  48190. };
  48191. this._onGesture = function (e) {
  48192. _this.camera.radius *= e.scale;
  48193. if (e.preventDefault) {
  48194. if (!noPreventDefault) {
  48195. e.stopPropagation();
  48196. e.preventDefault();
  48197. }
  48198. }
  48199. };
  48200. element.addEventListener("mousemove", this._onMouseMove, false);
  48201. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48202. element.addEventListener("MSGestureChange", this._onGesture, false);
  48203. BABYLON.Tools.RegisterTopRootEvents([
  48204. { name: "blur", handler: this._onLostFocus }
  48205. ]);
  48206. };
  48207. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48208. if (this._onLostFocus) {
  48209. BABYLON.Tools.UnregisterTopRootEvents([
  48210. { name: "blur", handler: this._onLostFocus }
  48211. ]);
  48212. }
  48213. if (element && this._observer) {
  48214. this.camera.getScene().onPointerObservable.remove(this._observer);
  48215. this._observer = null;
  48216. if (this._onContextMenu) {
  48217. element.removeEventListener("contextmenu", this._onContextMenu);
  48218. }
  48219. if (this._onMouseMove) {
  48220. element.removeEventListener("mousemove", this._onMouseMove);
  48221. }
  48222. if (this._onGestureStart) {
  48223. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48224. }
  48225. if (this._onGesture) {
  48226. element.removeEventListener("MSGestureChange", this._onGesture);
  48227. }
  48228. this._isPanClick = false;
  48229. this.pinchInwards = true;
  48230. this._onMouseMove = null;
  48231. this._onGestureStart = null;
  48232. this._onGesture = null;
  48233. this._MSGestureHandler = null;
  48234. this._onLostFocus = null;
  48235. this._onContextMenu = null;
  48236. }
  48237. };
  48238. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48239. return "ArcRotateCameraPointersInput";
  48240. };
  48241. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48242. return "pointers";
  48243. };
  48244. __decorate([
  48245. BABYLON.serialize()
  48246. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48247. __decorate([
  48248. BABYLON.serialize()
  48249. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48250. __decorate([
  48251. BABYLON.serialize()
  48252. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48253. __decorate([
  48254. BABYLON.serialize()
  48255. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48259. __decorate([
  48260. BABYLON.serialize()
  48261. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48262. __decorate([
  48263. BABYLON.serialize()
  48264. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48265. __decorate([
  48266. BABYLON.serialize()
  48267. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48268. return ArcRotateCameraPointersInput;
  48269. }());
  48270. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48271. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48272. })(BABYLON || (BABYLON = {}));
  48273. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48274. var BABYLON;
  48275. (function (BABYLON) {
  48276. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48277. __extends(ArcRotateCameraInputsManager, _super);
  48278. function ArcRotateCameraInputsManager(camera) {
  48279. return _super.call(this, camera) || this;
  48280. }
  48281. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48282. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48283. return this;
  48284. };
  48285. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48286. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48287. return this;
  48288. };
  48289. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48290. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48291. return this;
  48292. };
  48293. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48294. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48295. return this;
  48296. };
  48297. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48298. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48299. return this;
  48300. };
  48301. return ArcRotateCameraInputsManager;
  48302. }(BABYLON.CameraInputsManager));
  48303. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48304. })(BABYLON || (BABYLON = {}));
  48305. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48306. var BABYLON;
  48307. (function (BABYLON) {
  48308. var ArcRotateCamera = /** @class */ (function (_super) {
  48309. __extends(ArcRotateCamera, _super);
  48310. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48311. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48312. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48313. _this.inertialAlphaOffset = 0;
  48314. _this.inertialBetaOffset = 0;
  48315. _this.inertialRadiusOffset = 0;
  48316. _this.lowerAlphaLimit = null;
  48317. _this.upperAlphaLimit = null;
  48318. _this.lowerBetaLimit = 0.01;
  48319. _this.upperBetaLimit = Math.PI;
  48320. _this.lowerRadiusLimit = null;
  48321. _this.upperRadiusLimit = null;
  48322. _this.inertialPanningX = 0;
  48323. _this.inertialPanningY = 0;
  48324. _this.pinchToPanMaxDistance = 20;
  48325. _this.panningDistanceLimit = null;
  48326. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48327. _this.panningInertia = 0.9;
  48328. //-- end properties for backward compatibility for inputs
  48329. _this.zoomOnFactor = 1;
  48330. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48331. _this.allowUpsideDown = true;
  48332. _this._viewMatrix = new BABYLON.Matrix();
  48333. // Panning
  48334. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48335. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48336. _this.checkCollisions = false;
  48337. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48338. _this._previousPosition = BABYLON.Vector3.Zero();
  48339. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48340. _this._newPosition = BABYLON.Vector3.Zero();
  48341. _this._computationVector = BABYLON.Vector3.Zero();
  48342. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48343. if (collidedMesh === void 0) { collidedMesh = null; }
  48344. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48345. newPosition.multiplyInPlace(_this._collider._radius);
  48346. }
  48347. if (!collidedMesh) {
  48348. _this._previousPosition.copyFrom(_this.position);
  48349. }
  48350. else {
  48351. _this.setPosition(newPosition);
  48352. if (_this.onCollide) {
  48353. _this.onCollide(collidedMesh);
  48354. }
  48355. }
  48356. // Recompute because of constraints
  48357. var cosa = Math.cos(_this.alpha);
  48358. var sina = Math.sin(_this.alpha);
  48359. var cosb = Math.cos(_this.beta);
  48360. var sinb = Math.sin(_this.beta);
  48361. if (sinb === 0) {
  48362. sinb = 0.0001;
  48363. }
  48364. var target = _this._getTargetPosition();
  48365. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48366. target.addToRef(_this._computationVector, _this._newPosition);
  48367. _this.position.copyFrom(_this._newPosition);
  48368. var up = _this.upVector;
  48369. if (_this.allowUpsideDown && _this.beta < 0) {
  48370. up = up.clone();
  48371. up = up.negate();
  48372. }
  48373. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48374. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48375. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48376. _this._collisionTriggered = false;
  48377. };
  48378. _this._target = BABYLON.Vector3.Zero();
  48379. if (target) {
  48380. _this.setTarget(target);
  48381. }
  48382. _this.alpha = alpha;
  48383. _this.beta = beta;
  48384. _this.radius = radius;
  48385. _this.getViewMatrix();
  48386. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48387. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48388. return _this;
  48389. }
  48390. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48391. get: function () {
  48392. return this._target;
  48393. },
  48394. set: function (value) {
  48395. this.setTarget(value);
  48396. },
  48397. enumerable: true,
  48398. configurable: true
  48399. });
  48400. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48401. //-- begin properties for backward compatibility for inputs
  48402. get: function () {
  48403. var pointers = this.inputs.attached["pointers"];
  48404. if (pointers)
  48405. return pointers.angularSensibilityX;
  48406. return 0;
  48407. },
  48408. set: function (value) {
  48409. var pointers = this.inputs.attached["pointers"];
  48410. if (pointers) {
  48411. pointers.angularSensibilityX = value;
  48412. }
  48413. },
  48414. enumerable: true,
  48415. configurable: true
  48416. });
  48417. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48418. get: function () {
  48419. var pointers = this.inputs.attached["pointers"];
  48420. if (pointers)
  48421. return pointers.angularSensibilityY;
  48422. return 0;
  48423. },
  48424. set: function (value) {
  48425. var pointers = this.inputs.attached["pointers"];
  48426. if (pointers) {
  48427. pointers.angularSensibilityY = value;
  48428. }
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48434. get: function () {
  48435. var pointers = this.inputs.attached["pointers"];
  48436. if (pointers)
  48437. return pointers.pinchPrecision;
  48438. return 0;
  48439. },
  48440. set: function (value) {
  48441. var pointers = this.inputs.attached["pointers"];
  48442. if (pointers) {
  48443. pointers.pinchPrecision = value;
  48444. }
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48450. get: function () {
  48451. var pointers = this.inputs.attached["pointers"];
  48452. if (pointers)
  48453. return pointers.pinchDeltaPercentage;
  48454. return 0;
  48455. },
  48456. set: function (value) {
  48457. var pointers = this.inputs.attached["pointers"];
  48458. if (pointers) {
  48459. pointers.pinchDeltaPercentage = value;
  48460. }
  48461. },
  48462. enumerable: true,
  48463. configurable: true
  48464. });
  48465. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48466. get: function () {
  48467. var pointers = this.inputs.attached["pointers"];
  48468. if (pointers)
  48469. return pointers.panningSensibility;
  48470. return 0;
  48471. },
  48472. set: function (value) {
  48473. var pointers = this.inputs.attached["pointers"];
  48474. if (pointers) {
  48475. pointers.panningSensibility = value;
  48476. }
  48477. },
  48478. enumerable: true,
  48479. configurable: true
  48480. });
  48481. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48482. get: function () {
  48483. var keyboard = this.inputs.attached["keyboard"];
  48484. if (keyboard)
  48485. return keyboard.keysUp;
  48486. return [];
  48487. },
  48488. set: function (value) {
  48489. var keyboard = this.inputs.attached["keyboard"];
  48490. if (keyboard)
  48491. keyboard.keysUp = value;
  48492. },
  48493. enumerable: true,
  48494. configurable: true
  48495. });
  48496. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48497. get: function () {
  48498. var keyboard = this.inputs.attached["keyboard"];
  48499. if (keyboard)
  48500. return keyboard.keysDown;
  48501. return [];
  48502. },
  48503. set: function (value) {
  48504. var keyboard = this.inputs.attached["keyboard"];
  48505. if (keyboard)
  48506. keyboard.keysDown = value;
  48507. },
  48508. enumerable: true,
  48509. configurable: true
  48510. });
  48511. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48512. get: function () {
  48513. var keyboard = this.inputs.attached["keyboard"];
  48514. if (keyboard)
  48515. return keyboard.keysLeft;
  48516. return [];
  48517. },
  48518. set: function (value) {
  48519. var keyboard = this.inputs.attached["keyboard"];
  48520. if (keyboard)
  48521. keyboard.keysLeft = value;
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48527. get: function () {
  48528. var keyboard = this.inputs.attached["keyboard"];
  48529. if (keyboard)
  48530. return keyboard.keysRight;
  48531. return [];
  48532. },
  48533. set: function (value) {
  48534. var keyboard = this.inputs.attached["keyboard"];
  48535. if (keyboard)
  48536. keyboard.keysRight = value;
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48542. get: function () {
  48543. var mousewheel = this.inputs.attached["mousewheel"];
  48544. if (mousewheel)
  48545. return mousewheel.wheelPrecision;
  48546. return 0;
  48547. },
  48548. set: function (value) {
  48549. var mousewheel = this.inputs.attached["mousewheel"];
  48550. if (mousewheel)
  48551. mousewheel.wheelPrecision = value;
  48552. },
  48553. enumerable: true,
  48554. configurable: true
  48555. });
  48556. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48557. get: function () {
  48558. var mousewheel = this.inputs.attached["mousewheel"];
  48559. if (mousewheel)
  48560. return mousewheel.wheelDeltaPercentage;
  48561. return 0;
  48562. },
  48563. set: function (value) {
  48564. var mousewheel = this.inputs.attached["mousewheel"];
  48565. if (mousewheel)
  48566. mousewheel.wheelDeltaPercentage = value;
  48567. },
  48568. enumerable: true,
  48569. configurable: true
  48570. });
  48571. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48572. get: function () {
  48573. return this._bouncingBehavior;
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48579. get: function () {
  48580. return this._bouncingBehavior != null;
  48581. },
  48582. set: function (value) {
  48583. if (value === this.useBouncingBehavior) {
  48584. return;
  48585. }
  48586. if (value) {
  48587. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48588. this.addBehavior(this._bouncingBehavior);
  48589. }
  48590. else if (this._bouncingBehavior) {
  48591. this.removeBehavior(this._bouncingBehavior);
  48592. this._bouncingBehavior = null;
  48593. }
  48594. },
  48595. enumerable: true,
  48596. configurable: true
  48597. });
  48598. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48599. get: function () {
  48600. return this._framingBehavior;
  48601. },
  48602. enumerable: true,
  48603. configurable: true
  48604. });
  48605. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48606. get: function () {
  48607. return this._framingBehavior != null;
  48608. },
  48609. set: function (value) {
  48610. if (value === this.useFramingBehavior) {
  48611. return;
  48612. }
  48613. if (value) {
  48614. this._framingBehavior = new BABYLON.FramingBehavior();
  48615. this.addBehavior(this._framingBehavior);
  48616. }
  48617. else if (this._framingBehavior) {
  48618. this.removeBehavior(this._framingBehavior);
  48619. this._framingBehavior = null;
  48620. }
  48621. },
  48622. enumerable: true,
  48623. configurable: true
  48624. });
  48625. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48626. get: function () {
  48627. return this._autoRotationBehavior;
  48628. },
  48629. enumerable: true,
  48630. configurable: true
  48631. });
  48632. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48633. get: function () {
  48634. return this._autoRotationBehavior != null;
  48635. },
  48636. set: function (value) {
  48637. if (value === this.useAutoRotationBehavior) {
  48638. return;
  48639. }
  48640. if (value) {
  48641. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48642. this.addBehavior(this._autoRotationBehavior);
  48643. }
  48644. else if (this._autoRotationBehavior) {
  48645. this.removeBehavior(this._autoRotationBehavior);
  48646. this._autoRotationBehavior = null;
  48647. }
  48648. },
  48649. enumerable: true,
  48650. configurable: true
  48651. });
  48652. // Cache
  48653. ArcRotateCamera.prototype._initCache = function () {
  48654. _super.prototype._initCache.call(this);
  48655. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48656. this._cache.alpha = undefined;
  48657. this._cache.beta = undefined;
  48658. this._cache.radius = undefined;
  48659. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48660. };
  48661. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48662. if (!ignoreParentClass) {
  48663. _super.prototype._updateCache.call(this);
  48664. }
  48665. this._cache._target.copyFrom(this._getTargetPosition());
  48666. this._cache.alpha = this.alpha;
  48667. this._cache.beta = this.beta;
  48668. this._cache.radius = this.radius;
  48669. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48670. };
  48671. ArcRotateCamera.prototype._getTargetPosition = function () {
  48672. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48673. var pos = this._targetHost.getAbsolutePosition();
  48674. if (this._targetBoundingCenter) {
  48675. pos.addToRef(this._targetBoundingCenter, this._target);
  48676. }
  48677. else {
  48678. this._target.copyFrom(pos);
  48679. }
  48680. }
  48681. var lockedTargetPosition = this._getLockedTargetPosition();
  48682. if (lockedTargetPosition) {
  48683. return lockedTargetPosition;
  48684. }
  48685. return this._target;
  48686. };
  48687. ArcRotateCamera.prototype.storeState = function () {
  48688. this._storedAlpha = this.alpha;
  48689. this._storedBeta = this.beta;
  48690. this._storedRadius = this.radius;
  48691. this._storedTarget = this._getTargetPosition().clone();
  48692. return _super.prototype.storeState.call(this);
  48693. };
  48694. /**
  48695. * Restored camera state. You must call storeState() first
  48696. */
  48697. ArcRotateCamera.prototype._restoreStateValues = function () {
  48698. if (!_super.prototype._restoreStateValues.call(this)) {
  48699. return false;
  48700. }
  48701. this.alpha = this._storedAlpha;
  48702. this.beta = this._storedBeta;
  48703. this.radius = this._storedRadius;
  48704. this.setTarget(this._storedTarget.clone());
  48705. this.inertialAlphaOffset = 0;
  48706. this.inertialBetaOffset = 0;
  48707. this.inertialRadiusOffset = 0;
  48708. this.inertialPanningX = 0;
  48709. this.inertialPanningY = 0;
  48710. return true;
  48711. };
  48712. // Synchronized
  48713. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48714. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48715. return false;
  48716. return this._cache._target.equals(this._getTargetPosition())
  48717. && this._cache.alpha === this.alpha
  48718. && this._cache.beta === this.beta
  48719. && this._cache.radius === this.radius
  48720. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48721. };
  48722. // Methods
  48723. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48724. var _this = this;
  48725. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48726. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48727. this._useCtrlForPanning = useCtrlForPanning;
  48728. this._panningMouseButton = panningMouseButton;
  48729. this.inputs.attachElement(element, noPreventDefault);
  48730. this._reset = function () {
  48731. _this.inertialAlphaOffset = 0;
  48732. _this.inertialBetaOffset = 0;
  48733. _this.inertialRadiusOffset = 0;
  48734. _this.inertialPanningX = 0;
  48735. _this.inertialPanningY = 0;
  48736. };
  48737. };
  48738. ArcRotateCamera.prototype.detachControl = function (element) {
  48739. this.inputs.detachElement(element);
  48740. if (this._reset) {
  48741. this._reset();
  48742. }
  48743. };
  48744. ArcRotateCamera.prototype._checkInputs = function () {
  48745. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48746. if (this._collisionTriggered) {
  48747. return;
  48748. }
  48749. this.inputs.checkInputs();
  48750. // Inertia
  48751. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48752. var inertialAlphaOffset = this.inertialAlphaOffset;
  48753. if (this.beta <= 0)
  48754. inertialAlphaOffset *= -1;
  48755. if (this.getScene().useRightHandedSystem)
  48756. inertialAlphaOffset *= -1;
  48757. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48758. inertialAlphaOffset *= -1;
  48759. this.alpha += inertialAlphaOffset;
  48760. this.beta += this.inertialBetaOffset;
  48761. this.radius -= this.inertialRadiusOffset;
  48762. this.inertialAlphaOffset *= this.inertia;
  48763. this.inertialBetaOffset *= this.inertia;
  48764. this.inertialRadiusOffset *= this.inertia;
  48765. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48766. this.inertialAlphaOffset = 0;
  48767. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48768. this.inertialBetaOffset = 0;
  48769. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48770. this.inertialRadiusOffset = 0;
  48771. }
  48772. // Panning inertia
  48773. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48774. if (!this._localDirection) {
  48775. this._localDirection = BABYLON.Vector3.Zero();
  48776. this._transformedDirection = BABYLON.Vector3.Zero();
  48777. }
  48778. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48779. this._localDirection.multiplyInPlace(this.panningAxis);
  48780. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48781. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48782. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48783. if (!this.panningAxis.y) {
  48784. this._transformedDirection.y = 0;
  48785. }
  48786. if (!this._targetHost) {
  48787. if (this.panningDistanceLimit) {
  48788. this._transformedDirection.addInPlace(this._target);
  48789. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48790. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48791. this._target.copyFrom(this._transformedDirection);
  48792. }
  48793. }
  48794. else {
  48795. this._target.addInPlace(this._transformedDirection);
  48796. }
  48797. }
  48798. this.inertialPanningX *= this.panningInertia;
  48799. this.inertialPanningY *= this.panningInertia;
  48800. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48801. this.inertialPanningX = 0;
  48802. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48803. this.inertialPanningY = 0;
  48804. }
  48805. // Limits
  48806. this._checkLimits();
  48807. _super.prototype._checkInputs.call(this);
  48808. };
  48809. ArcRotateCamera.prototype._checkLimits = function () {
  48810. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48811. if (this.allowUpsideDown && this.beta > Math.PI) {
  48812. this.beta = this.beta - (2 * Math.PI);
  48813. }
  48814. }
  48815. else {
  48816. if (this.beta < this.lowerBetaLimit) {
  48817. this.beta = this.lowerBetaLimit;
  48818. }
  48819. }
  48820. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48821. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48822. this.beta = this.beta + (2 * Math.PI);
  48823. }
  48824. }
  48825. else {
  48826. if (this.beta > this.upperBetaLimit) {
  48827. this.beta = this.upperBetaLimit;
  48828. }
  48829. }
  48830. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48831. this.alpha = this.lowerAlphaLimit;
  48832. }
  48833. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48834. this.alpha = this.upperAlphaLimit;
  48835. }
  48836. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48837. this.radius = this.lowerRadiusLimit;
  48838. }
  48839. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48840. this.radius = this.upperRadiusLimit;
  48841. }
  48842. };
  48843. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48844. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48845. this.radius = this._computationVector.length();
  48846. if (this.radius === 0) {
  48847. this.radius = 0.0001; // Just to avoid division by zero
  48848. }
  48849. // Alpha
  48850. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48851. if (this._computationVector.z < 0) {
  48852. this.alpha = 2 * Math.PI - this.alpha;
  48853. }
  48854. // Beta
  48855. this.beta = Math.acos(this._computationVector.y / this.radius);
  48856. this._checkLimits();
  48857. };
  48858. ArcRotateCamera.prototype.setPosition = function (position) {
  48859. if (this.position.equals(position)) {
  48860. return;
  48861. }
  48862. this.position.copyFrom(position);
  48863. this.rebuildAnglesAndRadius();
  48864. };
  48865. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48866. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48867. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48868. if (target.getBoundingInfo) {
  48869. if (toBoundingCenter) {
  48870. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48871. }
  48872. else {
  48873. this._targetBoundingCenter = null;
  48874. }
  48875. this._targetHost = target;
  48876. this._target = this._getTargetPosition();
  48877. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48878. }
  48879. else {
  48880. var newTarget = target;
  48881. var currentTarget = this._getTargetPosition();
  48882. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48883. return;
  48884. }
  48885. this._targetHost = null;
  48886. this._target = newTarget;
  48887. this._targetBoundingCenter = null;
  48888. this.onMeshTargetChangedObservable.notifyObservers(null);
  48889. }
  48890. this.rebuildAnglesAndRadius();
  48891. };
  48892. ArcRotateCamera.prototype._getViewMatrix = function () {
  48893. // Compute
  48894. var cosa = Math.cos(this.alpha);
  48895. var sina = Math.sin(this.alpha);
  48896. var cosb = Math.cos(this.beta);
  48897. var sinb = Math.sin(this.beta);
  48898. if (sinb === 0) {
  48899. sinb = 0.0001;
  48900. }
  48901. var target = this._getTargetPosition();
  48902. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48903. target.addToRef(this._computationVector, this._newPosition);
  48904. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48905. if (!this._collider) {
  48906. this._collider = new BABYLON.Collider();
  48907. }
  48908. this._collider._radius = this.collisionRadius;
  48909. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48910. this._collisionTriggered = true;
  48911. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48912. }
  48913. else {
  48914. this.position.copyFrom(this._newPosition);
  48915. var up = this.upVector;
  48916. if (this.allowUpsideDown && sinb < 0) {
  48917. up = up.clone();
  48918. up = up.negate();
  48919. }
  48920. this._computeViewMatrix(this.position, target, up);
  48921. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48922. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48923. }
  48924. this._currentTarget = target;
  48925. return this._viewMatrix;
  48926. };
  48927. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48928. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48929. meshes = meshes || this.getScene().meshes;
  48930. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48931. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48932. this.radius = distance * this.zoomOnFactor;
  48933. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48934. };
  48935. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48936. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48937. var meshesOrMinMaxVector;
  48938. var distance;
  48939. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48940. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48941. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48942. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48943. }
  48944. else { //minMaxVector and distance
  48945. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48946. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48947. distance = minMaxVectorAndDistance.distance;
  48948. }
  48949. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48950. if (!doNotUpdateMaxZ) {
  48951. this.maxZ = distance * 2;
  48952. }
  48953. };
  48954. /**
  48955. * @override
  48956. * Override Camera.createRigCamera
  48957. */
  48958. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48959. var alphaShift = 0;
  48960. switch (this.cameraRigMode) {
  48961. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48962. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48963. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48964. case BABYLON.Camera.RIG_MODE_VR:
  48965. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48966. break;
  48967. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48968. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48969. break;
  48970. }
  48971. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48972. rigCam._cameraRigParams = {};
  48973. return rigCam;
  48974. };
  48975. /**
  48976. * @override
  48977. * Override Camera._updateRigCameras
  48978. */
  48979. ArcRotateCamera.prototype._updateRigCameras = function () {
  48980. var camLeft = this._rigCameras[0];
  48981. var camRight = this._rigCameras[1];
  48982. camLeft.beta = camRight.beta = this.beta;
  48983. camLeft.radius = camRight.radius = this.radius;
  48984. switch (this.cameraRigMode) {
  48985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48988. case BABYLON.Camera.RIG_MODE_VR:
  48989. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48990. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48991. break;
  48992. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48993. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48994. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48995. break;
  48996. }
  48997. _super.prototype._updateRigCameras.call(this);
  48998. };
  48999. ArcRotateCamera.prototype.dispose = function () {
  49000. this.inputs.clear();
  49001. _super.prototype.dispose.call(this);
  49002. };
  49003. ArcRotateCamera.prototype.getClassName = function () {
  49004. return "ArcRotateCamera";
  49005. };
  49006. __decorate([
  49007. BABYLON.serialize()
  49008. ], ArcRotateCamera.prototype, "alpha", void 0);
  49009. __decorate([
  49010. BABYLON.serialize()
  49011. ], ArcRotateCamera.prototype, "beta", void 0);
  49012. __decorate([
  49013. BABYLON.serialize()
  49014. ], ArcRotateCamera.prototype, "radius", void 0);
  49015. __decorate([
  49016. BABYLON.serializeAsVector3("target")
  49017. ], ArcRotateCamera.prototype, "_target", void 0);
  49018. __decorate([
  49019. BABYLON.serialize()
  49020. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49021. __decorate([
  49022. BABYLON.serialize()
  49023. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49024. __decorate([
  49025. BABYLON.serialize()
  49026. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49027. __decorate([
  49028. BABYLON.serialize()
  49029. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49030. __decorate([
  49031. BABYLON.serialize()
  49032. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49033. __decorate([
  49034. BABYLON.serialize()
  49035. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49036. __decorate([
  49037. BABYLON.serialize()
  49038. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49039. __decorate([
  49040. BABYLON.serialize()
  49041. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49042. __decorate([
  49043. BABYLON.serialize()
  49044. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49045. __decorate([
  49046. BABYLON.serialize()
  49047. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49048. __decorate([
  49049. BABYLON.serialize()
  49050. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49051. __decorate([
  49052. BABYLON.serialize()
  49053. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49054. __decorate([
  49055. BABYLON.serialize()
  49056. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49057. __decorate([
  49058. BABYLON.serializeAsVector3()
  49059. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49060. __decorate([
  49061. BABYLON.serialize()
  49062. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49063. __decorate([
  49064. BABYLON.serialize()
  49065. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49066. __decorate([
  49067. BABYLON.serialize()
  49068. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49069. return ArcRotateCamera;
  49070. }(BABYLON.TargetCamera));
  49071. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49072. })(BABYLON || (BABYLON = {}));
  49073. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49074. var BABYLON;
  49075. (function (BABYLON) {
  49076. /**
  49077. * The HemisphericLight simulates the ambient environment light,
  49078. * so the passed direction is the light reflection direction, not the incoming direction.
  49079. */
  49080. var HemisphericLight = /** @class */ (function (_super) {
  49081. __extends(HemisphericLight, _super);
  49082. /**
  49083. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49084. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49085. * The HemisphericLight can't cast shadows.
  49086. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49087. * @param name The friendly name of the light
  49088. * @param direction The direction of the light reflection
  49089. * @param scene The scene the light belongs to
  49090. */
  49091. function HemisphericLight(name, direction, scene) {
  49092. var _this = _super.call(this, name, scene) || this;
  49093. /**
  49094. * The groundColor is the light in the opposite direction to the one specified during creation.
  49095. * 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.
  49096. */
  49097. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49098. _this.direction = direction || BABYLON.Vector3.Up();
  49099. return _this;
  49100. }
  49101. HemisphericLight.prototype._buildUniformLayout = function () {
  49102. this._uniformBuffer.addUniform("vLightData", 4);
  49103. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49104. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49105. this._uniformBuffer.addUniform("vLightGround", 3);
  49106. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49107. this._uniformBuffer.addUniform("depthValues", 2);
  49108. this._uniformBuffer.create();
  49109. };
  49110. /**
  49111. * Returns the string "HemisphericLight".
  49112. * @return The class name
  49113. */
  49114. HemisphericLight.prototype.getClassName = function () {
  49115. return "HemisphericLight";
  49116. };
  49117. /**
  49118. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49119. * Returns the updated direction.
  49120. * @param target The target the direction should point to
  49121. * @return The computed direction
  49122. */
  49123. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49124. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49125. return this.direction;
  49126. };
  49127. /**
  49128. * Returns the shadow generator associated to the light.
  49129. * @returns Always null for hemispheric lights because it does not support shadows.
  49130. */
  49131. HemisphericLight.prototype.getShadowGenerator = function () {
  49132. return null;
  49133. };
  49134. /**
  49135. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49136. * @param effect The effect to update
  49137. * @param lightIndex The index of the light in the effect to update
  49138. * @returns The hemispheric light
  49139. */
  49140. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49141. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49142. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49143. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49144. return this;
  49145. };
  49146. /**
  49147. * @hidden internal use only.
  49148. */
  49149. HemisphericLight.prototype._getWorldMatrix = function () {
  49150. if (!this._worldMatrix) {
  49151. this._worldMatrix = BABYLON.Matrix.Identity();
  49152. }
  49153. return this._worldMatrix;
  49154. };
  49155. /**
  49156. * Returns the integer 3.
  49157. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49158. */
  49159. HemisphericLight.prototype.getTypeID = function () {
  49160. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49161. };
  49162. __decorate([
  49163. BABYLON.serializeAsColor3()
  49164. ], HemisphericLight.prototype, "groundColor", void 0);
  49165. __decorate([
  49166. BABYLON.serializeAsVector3()
  49167. ], HemisphericLight.prototype, "direction", void 0);
  49168. return HemisphericLight;
  49169. }(BABYLON.Light));
  49170. BABYLON.HemisphericLight = HemisphericLight;
  49171. })(BABYLON || (BABYLON = {}));
  49172. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49173. var BABYLON;
  49174. (function (BABYLON) {
  49175. /**
  49176. * Base implementation IShadowLight
  49177. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49178. */
  49179. var ShadowLight = /** @class */ (function (_super) {
  49180. __extends(ShadowLight, _super);
  49181. function ShadowLight() {
  49182. var _this = _super !== null && _super.apply(this, arguments) || this;
  49183. _this._needProjectionMatrixCompute = true;
  49184. return _this;
  49185. }
  49186. ShadowLight.prototype._setPosition = function (value) {
  49187. this._position = value;
  49188. };
  49189. Object.defineProperty(ShadowLight.prototype, "position", {
  49190. /**
  49191. * Sets the position the shadow will be casted from. Also use as the light position for both
  49192. * point and spot lights.
  49193. */
  49194. get: function () {
  49195. return this._position;
  49196. },
  49197. /**
  49198. * Sets the position the shadow will be casted from. Also use as the light position for both
  49199. * point and spot lights.
  49200. */
  49201. set: function (value) {
  49202. this._setPosition(value);
  49203. },
  49204. enumerable: true,
  49205. configurable: true
  49206. });
  49207. ShadowLight.prototype._setDirection = function (value) {
  49208. this._direction = value;
  49209. };
  49210. Object.defineProperty(ShadowLight.prototype, "direction", {
  49211. /**
  49212. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49213. * Also use as the light direction on spot and directional lights.
  49214. */
  49215. get: function () {
  49216. return this._direction;
  49217. },
  49218. /**
  49219. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49220. * Also use as the light direction on spot and directional lights.
  49221. */
  49222. set: function (value) {
  49223. this._setDirection(value);
  49224. },
  49225. enumerable: true,
  49226. configurable: true
  49227. });
  49228. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49229. /**
  49230. * Gets the shadow projection clipping minimum z value.
  49231. */
  49232. get: function () {
  49233. return this._shadowMinZ;
  49234. },
  49235. /**
  49236. * Sets the shadow projection clipping minimum z value.
  49237. */
  49238. set: function (value) {
  49239. this._shadowMinZ = value;
  49240. this.forceProjectionMatrixCompute();
  49241. },
  49242. enumerable: true,
  49243. configurable: true
  49244. });
  49245. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49246. /**
  49247. * Sets the shadow projection clipping maximum z value.
  49248. */
  49249. get: function () {
  49250. return this._shadowMaxZ;
  49251. },
  49252. /**
  49253. * Gets the shadow projection clipping maximum z value.
  49254. */
  49255. set: function (value) {
  49256. this._shadowMaxZ = value;
  49257. this.forceProjectionMatrixCompute();
  49258. },
  49259. enumerable: true,
  49260. configurable: true
  49261. });
  49262. /**
  49263. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49264. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49265. */
  49266. ShadowLight.prototype.computeTransformedInformation = function () {
  49267. if (this.parent && this.parent.getWorldMatrix) {
  49268. if (!this.transformedPosition) {
  49269. this.transformedPosition = BABYLON.Vector3.Zero();
  49270. }
  49271. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49272. // In case the direction is present.
  49273. if (this.direction) {
  49274. if (!this.transformedDirection) {
  49275. this.transformedDirection = BABYLON.Vector3.Zero();
  49276. }
  49277. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49278. }
  49279. return true;
  49280. }
  49281. return false;
  49282. };
  49283. /**
  49284. * Return the depth scale used for the shadow map.
  49285. * @returns the depth scale.
  49286. */
  49287. ShadowLight.prototype.getDepthScale = function () {
  49288. return 50.0;
  49289. };
  49290. /**
  49291. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49292. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49293. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49294. */
  49295. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49296. return this.transformedDirection ? this.transformedDirection : this.direction;
  49297. };
  49298. /**
  49299. * Returns the ShadowLight absolute position in the World.
  49300. * @returns the position vector in world space
  49301. */
  49302. ShadowLight.prototype.getAbsolutePosition = function () {
  49303. return this.transformedPosition ? this.transformedPosition : this.position;
  49304. };
  49305. /**
  49306. * Sets the ShadowLight direction toward the passed target.
  49307. * @param target The point tot target in local space
  49308. * @returns the updated ShadowLight direction
  49309. */
  49310. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49311. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49312. return this.direction;
  49313. };
  49314. /**
  49315. * Returns the light rotation in euler definition.
  49316. * @returns the x y z rotation in local space.
  49317. */
  49318. ShadowLight.prototype.getRotation = function () {
  49319. this.direction.normalize();
  49320. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49321. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49322. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49323. };
  49324. /**
  49325. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49326. * @returns true if a cube texture needs to be use
  49327. */
  49328. ShadowLight.prototype.needCube = function () {
  49329. return false;
  49330. };
  49331. /**
  49332. * Detects if the projection matrix requires to be recomputed this frame.
  49333. * @returns true if it requires to be recomputed otherwise, false.
  49334. */
  49335. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49336. return this._needProjectionMatrixCompute;
  49337. };
  49338. /**
  49339. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49340. */
  49341. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49342. this._needProjectionMatrixCompute = true;
  49343. };
  49344. /**
  49345. * Get the world matrix of the sahdow lights.
  49346. * @hidden Internal Use Only
  49347. */
  49348. ShadowLight.prototype._getWorldMatrix = function () {
  49349. if (!this._worldMatrix) {
  49350. this._worldMatrix = BABYLON.Matrix.Identity();
  49351. }
  49352. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49353. return this._worldMatrix;
  49354. };
  49355. /**
  49356. * Gets the minZ used for shadow according to both the scene and the light.
  49357. * @param activeCamera The camera we are returning the min for
  49358. * @returns the depth min z
  49359. */
  49360. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49361. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49362. };
  49363. /**
  49364. * Gets the maxZ used for shadow according to both the scene and the light.
  49365. * @param activeCamera The camera we are returning the max for
  49366. * @returns the depth max z
  49367. */
  49368. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49369. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49370. };
  49371. /**
  49372. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49373. * @param matrix The materix to updated with the projection information
  49374. * @param viewMatrix The transform matrix of the light
  49375. * @param renderList The list of mesh to render in the map
  49376. * @returns The current light
  49377. */
  49378. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49379. if (this.customProjectionMatrixBuilder) {
  49380. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49381. }
  49382. else {
  49383. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49384. }
  49385. return this;
  49386. };
  49387. __decorate([
  49388. BABYLON.serializeAsVector3()
  49389. ], ShadowLight.prototype, "position", null);
  49390. __decorate([
  49391. BABYLON.serializeAsVector3()
  49392. ], ShadowLight.prototype, "direction", null);
  49393. __decorate([
  49394. BABYLON.serialize()
  49395. ], ShadowLight.prototype, "shadowMinZ", null);
  49396. __decorate([
  49397. BABYLON.serialize()
  49398. ], ShadowLight.prototype, "shadowMaxZ", null);
  49399. return ShadowLight;
  49400. }(BABYLON.Light));
  49401. BABYLON.ShadowLight = ShadowLight;
  49402. })(BABYLON || (BABYLON = {}));
  49403. //# sourceMappingURL=babylon.shadowLight.js.map
  49404. var BABYLON;
  49405. (function (BABYLON) {
  49406. /**
  49407. * A point light is a light defined by an unique point in world space.
  49408. * The light is emitted in every direction from this point.
  49409. * A good example of a point light is a standard light bulb.
  49410. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49411. */
  49412. var PointLight = /** @class */ (function (_super) {
  49413. __extends(PointLight, _super);
  49414. /**
  49415. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49416. * A PointLight emits the light in every direction.
  49417. * It can cast shadows.
  49418. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49419. * ```javascript
  49420. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49421. * ```
  49422. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49423. * @param name The light friendly name
  49424. * @param position The position of the point light in the scene
  49425. * @param scene The scene the lights belongs to
  49426. */
  49427. function PointLight(name, position, scene) {
  49428. var _this = _super.call(this, name, scene) || this;
  49429. _this._shadowAngle = Math.PI / 2;
  49430. _this.position = position;
  49431. return _this;
  49432. }
  49433. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49434. /**
  49435. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49436. * This specifies what angle the shadow will use to be created.
  49437. *
  49438. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49439. */
  49440. get: function () {
  49441. return this._shadowAngle;
  49442. },
  49443. /**
  49444. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49445. * This specifies what angle the shadow will use to be created.
  49446. *
  49447. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49448. */
  49449. set: function (value) {
  49450. this._shadowAngle = value;
  49451. this.forceProjectionMatrixCompute();
  49452. },
  49453. enumerable: true,
  49454. configurable: true
  49455. });
  49456. Object.defineProperty(PointLight.prototype, "direction", {
  49457. /**
  49458. * Gets the direction if it has been set.
  49459. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49460. */
  49461. get: function () {
  49462. return this._direction;
  49463. },
  49464. /**
  49465. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49466. */
  49467. set: function (value) {
  49468. var previousNeedCube = this.needCube();
  49469. this._direction = value;
  49470. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49471. this._shadowGenerator.recreateShadowMap();
  49472. }
  49473. },
  49474. enumerable: true,
  49475. configurable: true
  49476. });
  49477. /**
  49478. * Returns the string "PointLight"
  49479. * @returns the class name
  49480. */
  49481. PointLight.prototype.getClassName = function () {
  49482. return "PointLight";
  49483. };
  49484. /**
  49485. * Returns the integer 0.
  49486. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49487. */
  49488. PointLight.prototype.getTypeID = function () {
  49489. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49490. };
  49491. /**
  49492. * Specifies wether or not the shadowmap should be a cube texture.
  49493. * @returns true if the shadowmap needs to be a cube texture.
  49494. */
  49495. PointLight.prototype.needCube = function () {
  49496. return !this.direction;
  49497. };
  49498. /**
  49499. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49500. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49501. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49502. */
  49503. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49504. if (this.direction) {
  49505. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49506. }
  49507. else {
  49508. switch (faceIndex) {
  49509. case 0:
  49510. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49511. case 1:
  49512. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49513. case 2:
  49514. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49515. case 3:
  49516. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49517. case 4:
  49518. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49519. case 5:
  49520. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49521. }
  49522. }
  49523. return BABYLON.Vector3.Zero();
  49524. };
  49525. /**
  49526. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49527. * - fov = PI / 2
  49528. * - aspect ratio : 1.0
  49529. * - z-near and far equal to the active camera minZ and maxZ.
  49530. * Returns the PointLight.
  49531. */
  49532. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49533. var activeCamera = this.getScene().activeCamera;
  49534. if (!activeCamera) {
  49535. return;
  49536. }
  49537. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49538. };
  49539. PointLight.prototype._buildUniformLayout = function () {
  49540. this._uniformBuffer.addUniform("vLightData", 4);
  49541. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49542. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49543. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49544. this._uniformBuffer.addUniform("depthValues", 2);
  49545. this._uniformBuffer.create();
  49546. };
  49547. /**
  49548. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49549. * @param effect The effect to update
  49550. * @param lightIndex The index of the light in the effect to update
  49551. * @returns The point light
  49552. */
  49553. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49554. if (this.computeTransformedInformation()) {
  49555. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49556. return this;
  49557. }
  49558. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49559. return this;
  49560. };
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], PointLight.prototype, "shadowAngle", null);
  49564. return PointLight;
  49565. }(BABYLON.ShadowLight));
  49566. BABYLON.PointLight = PointLight;
  49567. })(BABYLON || (BABYLON = {}));
  49568. //# sourceMappingURL=babylon.pointLight.js.map
  49569. var BABYLON;
  49570. (function (BABYLON) {
  49571. /**
  49572. * A directional light is defined by a direction (what a surprise!).
  49573. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49574. * 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.
  49575. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49576. */
  49577. var DirectionalLight = /** @class */ (function (_super) {
  49578. __extends(DirectionalLight, _super);
  49579. /**
  49580. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49581. * The directional light is emitted from everywhere in the given direction.
  49582. * It can cast shawdows.
  49583. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49584. * @param name The friendly name of the light
  49585. * @param direction The direction of the light
  49586. * @param scene The scene the light belongs to
  49587. */
  49588. function DirectionalLight(name, direction, scene) {
  49589. var _this = _super.call(this, name, scene) || this;
  49590. _this._shadowFrustumSize = 0;
  49591. _this._shadowOrthoScale = 0.1;
  49592. /**
  49593. * Automatically compute the projection matrix to best fit (including all the casters)
  49594. * on each frame.
  49595. */
  49596. _this.autoUpdateExtends = true;
  49597. // Cache
  49598. _this._orthoLeft = Number.MAX_VALUE;
  49599. _this._orthoRight = Number.MIN_VALUE;
  49600. _this._orthoTop = Number.MIN_VALUE;
  49601. _this._orthoBottom = Number.MAX_VALUE;
  49602. _this.position = direction.scale(-1.0);
  49603. _this.direction = direction;
  49604. return _this;
  49605. }
  49606. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49607. /**
  49608. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49609. */
  49610. get: function () {
  49611. return this._shadowFrustumSize;
  49612. },
  49613. /**
  49614. * Specifies a fix frustum size for the shadow generation.
  49615. */
  49616. set: function (value) {
  49617. this._shadowFrustumSize = value;
  49618. this.forceProjectionMatrixCompute();
  49619. },
  49620. enumerable: true,
  49621. configurable: true
  49622. });
  49623. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49624. /**
  49625. * Gets the shadow projection scale against the optimal computed one.
  49626. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49627. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49628. */
  49629. get: function () {
  49630. return this._shadowOrthoScale;
  49631. },
  49632. /**
  49633. * Sets the shadow projection scale against the optimal computed one.
  49634. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49635. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49636. */
  49637. set: function (value) {
  49638. this._shadowOrthoScale = value;
  49639. this.forceProjectionMatrixCompute();
  49640. },
  49641. enumerable: true,
  49642. configurable: true
  49643. });
  49644. /**
  49645. * Returns the string "DirectionalLight".
  49646. * @return The class name
  49647. */
  49648. DirectionalLight.prototype.getClassName = function () {
  49649. return "DirectionalLight";
  49650. };
  49651. /**
  49652. * Returns the integer 1.
  49653. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49654. */
  49655. DirectionalLight.prototype.getTypeID = function () {
  49656. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49657. };
  49658. /**
  49659. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49660. * Returns the DirectionalLight Shadow projection matrix.
  49661. */
  49662. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49663. if (this.shadowFrustumSize > 0) {
  49664. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49665. }
  49666. else {
  49667. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49668. }
  49669. };
  49670. /**
  49671. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49672. * Returns the DirectionalLight Shadow projection matrix.
  49673. */
  49674. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49675. var activeCamera = this.getScene().activeCamera;
  49676. if (!activeCamera) {
  49677. return;
  49678. }
  49679. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49680. };
  49681. /**
  49682. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49683. * Returns the DirectionalLight Shadow projection matrix.
  49684. */
  49685. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49686. var activeCamera = this.getScene().activeCamera;
  49687. if (!activeCamera) {
  49688. return;
  49689. }
  49690. // Check extends
  49691. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49692. var tempVector3 = BABYLON.Vector3.Zero();
  49693. this._orthoLeft = Number.MAX_VALUE;
  49694. this._orthoRight = Number.MIN_VALUE;
  49695. this._orthoTop = Number.MIN_VALUE;
  49696. this._orthoBottom = Number.MAX_VALUE;
  49697. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49698. var mesh = renderList[meshIndex];
  49699. if (!mesh) {
  49700. continue;
  49701. }
  49702. var boundingInfo = mesh.getBoundingInfo();
  49703. var boundingBox = boundingInfo.boundingBox;
  49704. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49705. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49706. if (tempVector3.x < this._orthoLeft)
  49707. this._orthoLeft = tempVector3.x;
  49708. if (tempVector3.y < this._orthoBottom)
  49709. this._orthoBottom = tempVector3.y;
  49710. if (tempVector3.x > this._orthoRight)
  49711. this._orthoRight = tempVector3.x;
  49712. if (tempVector3.y > this._orthoTop)
  49713. this._orthoTop = tempVector3.y;
  49714. }
  49715. }
  49716. }
  49717. var xOffset = this._orthoRight - this._orthoLeft;
  49718. var yOffset = this._orthoTop - this._orthoBottom;
  49719. 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);
  49720. };
  49721. DirectionalLight.prototype._buildUniformLayout = function () {
  49722. this._uniformBuffer.addUniform("vLightData", 4);
  49723. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49724. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49725. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49726. this._uniformBuffer.addUniform("depthValues", 2);
  49727. this._uniformBuffer.create();
  49728. };
  49729. /**
  49730. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49731. * @param effect The effect to update
  49732. * @param lightIndex The index of the light in the effect to update
  49733. * @returns The directional light
  49734. */
  49735. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49736. if (this.computeTransformedInformation()) {
  49737. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49738. return this;
  49739. }
  49740. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49741. return this;
  49742. };
  49743. /**
  49744. * Gets the minZ used for shadow according to both the scene and the light.
  49745. *
  49746. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49747. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49748. * @param activeCamera The camera we are returning the min for
  49749. * @returns the depth min z
  49750. */
  49751. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49752. return 1;
  49753. };
  49754. /**
  49755. * Gets the maxZ used for shadow according to both the scene and the light.
  49756. *
  49757. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49758. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49759. * @param activeCamera The camera we are returning the max for
  49760. * @returns the depth max z
  49761. */
  49762. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49763. return 1;
  49764. };
  49765. __decorate([
  49766. BABYLON.serialize()
  49767. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49771. __decorate([
  49772. BABYLON.serialize()
  49773. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49774. return DirectionalLight;
  49775. }(BABYLON.ShadowLight));
  49776. BABYLON.DirectionalLight = DirectionalLight;
  49777. })(BABYLON || (BABYLON = {}));
  49778. //# sourceMappingURL=babylon.directionalLight.js.map
  49779. var BABYLON;
  49780. (function (BABYLON) {
  49781. /**
  49782. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49783. * These values define a cone of light starting from the position, emitting toward the direction.
  49784. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49785. * and the exponent defines the speed of the decay of the light with distance (reach).
  49786. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49787. */
  49788. var SpotLight = /** @class */ (function (_super) {
  49789. __extends(SpotLight, _super);
  49790. /**
  49791. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49792. * It can cast shadows.
  49793. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49794. * @param name The light friendly name
  49795. * @param position The position of the spot light in the scene
  49796. * @param direction The direction of the light in the scene
  49797. * @param angle The cone angle of the light in Radians
  49798. * @param exponent The light decay speed with the distance from the emission spot
  49799. * @param scene The scene the lights belongs to
  49800. */
  49801. function SpotLight(name, position, direction, angle, exponent, scene) {
  49802. var _this = _super.call(this, name, scene) || this;
  49803. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49804. _this._projectionTextureLightNear = 1e-6;
  49805. _this._projectionTextureLightFar = 1000.0;
  49806. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49807. _this._projectionTextureViewLightDirty = true;
  49808. _this._projectionTextureProjectionLightDirty = true;
  49809. _this._projectionTextureDirty = true;
  49810. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49811. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49812. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49813. _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);
  49814. _this.position = position;
  49815. _this.direction = direction;
  49816. _this.angle = angle;
  49817. _this.exponent = exponent;
  49818. return _this;
  49819. }
  49820. Object.defineProperty(SpotLight.prototype, "angle", {
  49821. /**
  49822. * Gets the cone angle of the spot light in Radians.
  49823. */
  49824. get: function () {
  49825. return this._angle;
  49826. },
  49827. /**
  49828. * Sets the cone angle of the spot light in Radians.
  49829. */
  49830. set: function (value) {
  49831. this._angle = value;
  49832. this._projectionTextureProjectionLightDirty = true;
  49833. this.forceProjectionMatrixCompute();
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49839. /**
  49840. * Allows scaling the angle of the light for shadow generation only.
  49841. */
  49842. get: function () {
  49843. return this._shadowAngleScale;
  49844. },
  49845. /**
  49846. * Allows scaling the angle of the light for shadow generation only.
  49847. */
  49848. set: function (value) {
  49849. this._shadowAngleScale = value;
  49850. this.forceProjectionMatrixCompute();
  49851. },
  49852. enumerable: true,
  49853. configurable: true
  49854. });
  49855. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49856. /**
  49857. * Allows reading the projecton texture
  49858. */
  49859. get: function () {
  49860. return this._projectionTextureMatrix;
  49861. },
  49862. enumerable: true,
  49863. configurable: true
  49864. });
  49865. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49866. /**
  49867. * Gets the near clip of the Spotlight for texture projection.
  49868. */
  49869. get: function () {
  49870. return this._projectionTextureLightNear;
  49871. },
  49872. /**
  49873. * Sets the near clip of the Spotlight for texture projection.
  49874. */
  49875. set: function (value) {
  49876. this._projectionTextureLightNear = value;
  49877. this._projectionTextureProjectionLightDirty = true;
  49878. },
  49879. enumerable: true,
  49880. configurable: true
  49881. });
  49882. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49883. /**
  49884. * Gets the far clip of the Spotlight for texture projection.
  49885. */
  49886. get: function () {
  49887. return this._projectionTextureLightFar;
  49888. },
  49889. /**
  49890. * Sets the far clip of the Spotlight for texture projection.
  49891. */
  49892. set: function (value) {
  49893. this._projectionTextureLightFar = value;
  49894. this._projectionTextureProjectionLightDirty = true;
  49895. },
  49896. enumerable: true,
  49897. configurable: true
  49898. });
  49899. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49900. /**
  49901. * Gets the Up vector of the Spotlight for texture projection.
  49902. */
  49903. get: function () {
  49904. return this._projectionTextureUpDirection;
  49905. },
  49906. /**
  49907. * Sets the Up vector of the Spotlight for texture projection.
  49908. */
  49909. set: function (value) {
  49910. this._projectionTextureUpDirection = value;
  49911. this._projectionTextureProjectionLightDirty = true;
  49912. },
  49913. enumerable: true,
  49914. configurable: true
  49915. });
  49916. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49917. /**
  49918. * Gets the projection texture of the light.
  49919. */
  49920. get: function () {
  49921. return this._projectionTexture;
  49922. },
  49923. /**
  49924. * Sets the projection texture of the light.
  49925. */
  49926. set: function (value) {
  49927. this._projectionTexture = value;
  49928. this._projectionTextureDirty = true;
  49929. },
  49930. enumerable: true,
  49931. configurable: true
  49932. });
  49933. /**
  49934. * Returns the string "SpotLight".
  49935. * @returns the class name
  49936. */
  49937. SpotLight.prototype.getClassName = function () {
  49938. return "SpotLight";
  49939. };
  49940. /**
  49941. * Returns the integer 2.
  49942. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49943. */
  49944. SpotLight.prototype.getTypeID = function () {
  49945. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49946. };
  49947. /**
  49948. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49949. */
  49950. SpotLight.prototype._setDirection = function (value) {
  49951. _super.prototype._setDirection.call(this, value);
  49952. this._projectionTextureViewLightDirty = true;
  49953. };
  49954. /**
  49955. * Overrides the position setter to recompute the projection texture view light Matrix.
  49956. */
  49957. SpotLight.prototype._setPosition = function (value) {
  49958. _super.prototype._setPosition.call(this, value);
  49959. this._projectionTextureViewLightDirty = true;
  49960. };
  49961. /**
  49962. * 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.
  49963. * Returns the SpotLight.
  49964. */
  49965. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49966. var activeCamera = this.getScene().activeCamera;
  49967. if (!activeCamera) {
  49968. return;
  49969. }
  49970. this._shadowAngleScale = this._shadowAngleScale || 1;
  49971. var angle = this._shadowAngleScale * this._angle;
  49972. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49973. };
  49974. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49975. this._projectionTextureViewLightDirty = false;
  49976. this._projectionTextureDirty = true;
  49977. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49978. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49979. };
  49980. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49981. this._projectionTextureProjectionLightDirty = false;
  49982. this._projectionTextureDirty = true;
  49983. var light_far = this.projectionTextureLightFar;
  49984. var light_near = this.projectionTextureLightNear;
  49985. var P = light_far / (light_far - light_near);
  49986. var Q = -P * light_near;
  49987. var S = 1.0 / Math.tan(this._angle / 2.0);
  49988. var A = 1.0;
  49989. 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);
  49990. };
  49991. /**
  49992. * Main function for light texture projection matrix computing.
  49993. */
  49994. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49995. this._projectionTextureDirty = false;
  49996. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49997. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49998. };
  49999. SpotLight.prototype._buildUniformLayout = function () {
  50000. this._uniformBuffer.addUniform("vLightData", 4);
  50001. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50002. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50003. this._uniformBuffer.addUniform("vLightDirection", 3);
  50004. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50005. this._uniformBuffer.addUniform("depthValues", 2);
  50006. this._uniformBuffer.create();
  50007. };
  50008. /**
  50009. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50010. * @param effect The effect to update
  50011. * @param lightIndex The index of the light in the effect to update
  50012. * @returns The spot light
  50013. */
  50014. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50015. var normalizeDirection;
  50016. if (this.computeTransformedInformation()) {
  50017. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50018. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50019. }
  50020. else {
  50021. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50022. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50023. }
  50024. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50025. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50026. if (this._projectionTextureViewLightDirty) {
  50027. this._computeProjectionTextureViewLightMatrix();
  50028. }
  50029. if (this._projectionTextureProjectionLightDirty) {
  50030. this._computeProjectionTextureProjectionLightMatrix();
  50031. }
  50032. if (this._projectionTextureDirty) {
  50033. this._computeProjectionTextureMatrix();
  50034. }
  50035. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50036. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50037. }
  50038. return this;
  50039. };
  50040. /**
  50041. * Disposes the light and the associated resources.
  50042. */
  50043. SpotLight.prototype.dispose = function () {
  50044. _super.prototype.dispose.call(this);
  50045. if (this._projectionTexture) {
  50046. this._projectionTexture.dispose();
  50047. }
  50048. };
  50049. __decorate([
  50050. BABYLON.serialize()
  50051. ], SpotLight.prototype, "angle", null);
  50052. __decorate([
  50053. BABYLON.serialize()
  50054. ], SpotLight.prototype, "shadowAngleScale", null);
  50055. __decorate([
  50056. BABYLON.serialize()
  50057. ], SpotLight.prototype, "exponent", void 0);
  50058. __decorate([
  50059. BABYLON.serialize()
  50060. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50061. __decorate([
  50062. BABYLON.serialize()
  50063. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50064. __decorate([
  50065. BABYLON.serialize()
  50066. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50067. __decorate([
  50068. BABYLON.serializeAsTexture("projectedLightTexture")
  50069. ], SpotLight.prototype, "_projectionTexture", void 0);
  50070. return SpotLight;
  50071. }(BABYLON.ShadowLight));
  50072. BABYLON.SpotLight = SpotLight;
  50073. })(BABYLON || (BABYLON = {}));
  50074. //# sourceMappingURL=babylon.spotLight.js.map
  50075. var BABYLON;
  50076. (function (BABYLON) {
  50077. /**
  50078. * Class used to override all child animations of a given target
  50079. */
  50080. var AnimationPropertiesOverride = /** @class */ (function () {
  50081. function AnimationPropertiesOverride() {
  50082. /**
  50083. * Gets or sets a value indicating if animation blending must be used
  50084. */
  50085. this.enableBlending = false;
  50086. /**
  50087. * Gets or sets the blending speed to use when enableBlending is true
  50088. */
  50089. this.blendingSpeed = 0.01;
  50090. /**
  50091. * Gets or sets the default loop mode to use
  50092. */
  50093. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50094. }
  50095. return AnimationPropertiesOverride;
  50096. }());
  50097. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50098. })(BABYLON || (BABYLON = {}));
  50099. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50100. var BABYLON;
  50101. (function (BABYLON) {
  50102. /**
  50103. * Represents the range of an animation
  50104. */
  50105. var AnimationRange = /** @class */ (function () {
  50106. /**
  50107. * Initializes the range of an animation
  50108. * @param name The name of the animation range
  50109. * @param from The starting frame of the animation
  50110. * @param to The ending frame of the animation
  50111. */
  50112. function AnimationRange(
  50113. /**The name of the animation range**/
  50114. name,
  50115. /**The starting frame of the animation */
  50116. from,
  50117. /**The ending frame of the animation*/
  50118. to) {
  50119. this.name = name;
  50120. this.from = from;
  50121. this.to = to;
  50122. }
  50123. /**
  50124. * Makes a copy of the animation range
  50125. * @returns A copy of the animation range
  50126. */
  50127. AnimationRange.prototype.clone = function () {
  50128. return new AnimationRange(this.name, this.from, this.to);
  50129. };
  50130. return AnimationRange;
  50131. }());
  50132. BABYLON.AnimationRange = AnimationRange;
  50133. /**
  50134. * Composed of a frame, and an action function
  50135. */
  50136. var AnimationEvent = /** @class */ (function () {
  50137. /**
  50138. * Initializes the animation event
  50139. * @param frame The frame for which the event is triggered
  50140. * @param action The event to perform when triggered
  50141. * @param onlyOnce Specifies if the event should be triggered only once
  50142. */
  50143. function AnimationEvent(
  50144. /** The frame for which the event is triggered **/
  50145. frame,
  50146. /** The event to perform when triggered **/
  50147. action,
  50148. /** Specifies if the event should be triggered only once**/
  50149. onlyOnce) {
  50150. this.frame = frame;
  50151. this.action = action;
  50152. this.onlyOnce = onlyOnce;
  50153. /**
  50154. * Specifies if the animation event is done
  50155. */
  50156. this.isDone = false;
  50157. }
  50158. return AnimationEvent;
  50159. }());
  50160. BABYLON.AnimationEvent = AnimationEvent;
  50161. /**
  50162. * A cursor which tracks a point on a path
  50163. */
  50164. var PathCursor = /** @class */ (function () {
  50165. /**
  50166. * Initializes the path cursor
  50167. * @param path The path to track
  50168. */
  50169. function PathCursor(path) {
  50170. this.path = path;
  50171. /**
  50172. * Stores path cursor callbacks for when an onchange event is triggered
  50173. */
  50174. this._onchange = new Array();
  50175. /**
  50176. * The value of the path cursor
  50177. */
  50178. this.value = 0;
  50179. /**
  50180. * The animation array of the path cursor
  50181. */
  50182. this.animations = new Array();
  50183. }
  50184. /**
  50185. * Gets the cursor point on the path
  50186. * @returns A point on the path cursor at the cursor location
  50187. */
  50188. PathCursor.prototype.getPoint = function () {
  50189. var point = this.path.getPointAtLengthPosition(this.value);
  50190. return new BABYLON.Vector3(point.x, 0, point.y);
  50191. };
  50192. /**
  50193. * Moves the cursor ahead by the step amount
  50194. * @param step The amount to move the cursor forward
  50195. * @returns This path cursor
  50196. */
  50197. PathCursor.prototype.moveAhead = function (step) {
  50198. if (step === void 0) { step = 0.002; }
  50199. this.move(step);
  50200. return this;
  50201. };
  50202. /**
  50203. * Moves the cursor behind by the step amount
  50204. * @param step The amount to move the cursor back
  50205. * @returns This path cursor
  50206. */
  50207. PathCursor.prototype.moveBack = function (step) {
  50208. if (step === void 0) { step = 0.002; }
  50209. this.move(-step);
  50210. return this;
  50211. };
  50212. /**
  50213. * Moves the cursor by the step amount
  50214. * If the step amount is greater than one, an exception is thrown
  50215. * @param step The amount to move the cursor
  50216. * @returns This path cursor
  50217. */
  50218. PathCursor.prototype.move = function (step) {
  50219. if (Math.abs(step) > 1) {
  50220. throw "step size should be less than 1.";
  50221. }
  50222. this.value += step;
  50223. this.ensureLimits();
  50224. this.raiseOnChange();
  50225. return this;
  50226. };
  50227. /**
  50228. * Ensures that the value is limited between zero and one
  50229. * @returns This path cursor
  50230. */
  50231. PathCursor.prototype.ensureLimits = function () {
  50232. while (this.value > 1) {
  50233. this.value -= 1;
  50234. }
  50235. while (this.value < 0) {
  50236. this.value += 1;
  50237. }
  50238. return this;
  50239. };
  50240. /**
  50241. * Runs onchange callbacks on change (used by the animation engine)
  50242. * @returns This path cursor
  50243. */
  50244. PathCursor.prototype.raiseOnChange = function () {
  50245. var _this = this;
  50246. this._onchange.forEach(function (f) { return f(_this); });
  50247. return this;
  50248. };
  50249. /**
  50250. * Executes a function on change
  50251. * @param f A path cursor onchange callback
  50252. * @returns This path cursor
  50253. */
  50254. PathCursor.prototype.onchange = function (f) {
  50255. this._onchange.push(f);
  50256. return this;
  50257. };
  50258. return PathCursor;
  50259. }());
  50260. BABYLON.PathCursor = PathCursor;
  50261. /**
  50262. * Enum for the animation key frame interpolation type
  50263. */
  50264. var AnimationKeyInterpolation;
  50265. (function (AnimationKeyInterpolation) {
  50266. /**
  50267. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50268. */
  50269. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50270. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50271. /**
  50272. * Class used to store any kind of animation
  50273. */
  50274. var Animation = /** @class */ (function () {
  50275. /**
  50276. * Initializes the animation
  50277. * @param name Name of the animation
  50278. * @param targetProperty Property to animate
  50279. * @param framePerSecond The frames per second of the animation
  50280. * @param dataType The data type of the animation
  50281. * @param loopMode The loop mode of the animation
  50282. * @param enableBlendings Specifies if blending should be enabled
  50283. */
  50284. function Animation(
  50285. /**Name of the animation */
  50286. name,
  50287. /**Property to animate */
  50288. targetProperty,
  50289. /**The frames per second of the animation */
  50290. framePerSecond,
  50291. /**The data type of the animation */
  50292. dataType,
  50293. /**The loop mode of the animation */
  50294. loopMode,
  50295. /**Specifies if blending should be enabled */
  50296. enableBlending) {
  50297. this.name = name;
  50298. this.targetProperty = targetProperty;
  50299. this.framePerSecond = framePerSecond;
  50300. this.dataType = dataType;
  50301. this.loopMode = loopMode;
  50302. this.enableBlending = enableBlending;
  50303. /**
  50304. * @hidden Internal use only
  50305. */
  50306. this._runtimeAnimations = new Array();
  50307. /**
  50308. * The set of event that will be linked to this animation
  50309. */
  50310. this._events = new Array();
  50311. /**
  50312. * Stores the blending speed of the animation
  50313. */
  50314. this.blendingSpeed = 0.01;
  50315. /**
  50316. * Stores the animation ranges for the animation
  50317. */
  50318. this._ranges = {};
  50319. this.targetPropertyPath = targetProperty.split(".");
  50320. this.dataType = dataType;
  50321. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50322. }
  50323. /**
  50324. * @hidden Internal use
  50325. */
  50326. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50327. var dataType = undefined;
  50328. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50329. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50330. }
  50331. else if (from instanceof BABYLON.Quaternion) {
  50332. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50333. }
  50334. else if (from instanceof BABYLON.Vector3) {
  50335. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50336. }
  50337. else if (from instanceof BABYLON.Vector2) {
  50338. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50339. }
  50340. else if (from instanceof BABYLON.Color3) {
  50341. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50342. }
  50343. else if (from instanceof BABYLON.Size) {
  50344. dataType = Animation.ANIMATIONTYPE_SIZE;
  50345. }
  50346. if (dataType == undefined) {
  50347. return null;
  50348. }
  50349. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50350. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50351. animation.setKeys(keys);
  50352. if (easingFunction !== undefined) {
  50353. animation.setEasingFunction(easingFunction);
  50354. }
  50355. return animation;
  50356. };
  50357. /**
  50358. * Sets up an animation
  50359. * @param property The property to animate
  50360. * @param animationType The animation type to apply
  50361. * @param framePerSecond The frames per second of the animation
  50362. * @param easingFunction The easing function used in the animation
  50363. * @returns The created animation
  50364. */
  50365. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50366. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50367. animation.setEasingFunction(easingFunction);
  50368. return animation;
  50369. };
  50370. /**
  50371. * Create and start an animation on a node
  50372. * @param name defines the name of the global animation that will be run on all nodes
  50373. * @param node defines the root node where the animation will take place
  50374. * @param targetProperty defines property to animate
  50375. * @param framePerSecond defines the number of frame per second yo use
  50376. * @param totalFrame defines the number of frames in total
  50377. * @param from defines the initial value
  50378. * @param to defines the final value
  50379. * @param loopMode defines which loop mode you want to use (off by default)
  50380. * @param easingFunction defines the easing function to use (linear by default)
  50381. * @param onAnimationEnd defines the callback to call when animation end
  50382. * @returns the animatable created for this animation
  50383. */
  50384. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50385. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50386. if (!animation) {
  50387. return null;
  50388. }
  50389. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50390. };
  50391. /**
  50392. * Create and start an animation on a node and its descendants
  50393. * @param name defines the name of the global animation that will be run on all nodes
  50394. * @param node defines the root node where the animation will take place
  50395. * @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
  50396. * @param targetProperty defines property to animate
  50397. * @param framePerSecond defines the number of frame per second to use
  50398. * @param totalFrame defines the number of frames in total
  50399. * @param from defines the initial value
  50400. * @param to defines the final value
  50401. * @param loopMode defines which loop mode you want to use (off by default)
  50402. * @param easingFunction defines the easing function to use (linear by default)
  50403. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50404. * @returns the list of animatables created for all nodes
  50405. * @example https://www.babylonjs-playground.com/#MH0VLI
  50406. */
  50407. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50408. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50409. if (!animation) {
  50410. return null;
  50411. }
  50412. var scene = node.getScene();
  50413. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50414. };
  50415. /**
  50416. * Creates a new animation, merges it with the existing animations and starts it
  50417. * @param name Name of the animation
  50418. * @param node Node which contains the scene that begins the animations
  50419. * @param targetProperty Specifies which property to animate
  50420. * @param framePerSecond The frames per second of the animation
  50421. * @param totalFrame The total number of frames
  50422. * @param from The frame at the beginning of the animation
  50423. * @param to The frame at the end of the animation
  50424. * @param loopMode Specifies the loop mode of the animation
  50425. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50426. * @param onAnimationEnd Callback to run once the animation is complete
  50427. * @returns Nullable animation
  50428. */
  50429. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50430. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50431. if (!animation) {
  50432. return null;
  50433. }
  50434. node.animations.push(animation);
  50435. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50436. };
  50437. /**
  50438. * Transition property of the Camera to the target Value
  50439. * @param property The property to transition
  50440. * @param targetValue The target Value of the property
  50441. * @param host The object where the property to animate belongs
  50442. * @param scene Scene used to run the animation
  50443. * @param frameRate Framerate (in frame/s) to use
  50444. * @param transition The transition type we want to use
  50445. * @param duration The duration of the animation, in milliseconds
  50446. * @param onAnimationEnd Callback trigger at the end of the animation
  50447. * @returns Nullable animation
  50448. */
  50449. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50450. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50451. if (duration <= 0) {
  50452. host[property] = targetValue;
  50453. if (onAnimationEnd) {
  50454. onAnimationEnd();
  50455. }
  50456. return null;
  50457. }
  50458. var endFrame = frameRate * (duration / 1000);
  50459. transition.setKeys([{
  50460. frame: 0,
  50461. value: host[property].clone ? host[property].clone() : host[property]
  50462. },
  50463. {
  50464. frame: endFrame,
  50465. value: targetValue
  50466. }]);
  50467. if (!host.animations) {
  50468. host.animations = [];
  50469. }
  50470. host.animations.push(transition);
  50471. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50472. animation.onAnimationEnd = onAnimationEnd;
  50473. return animation;
  50474. };
  50475. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50476. /**
  50477. * Return the array of runtime animations currently using this animation
  50478. */
  50479. get: function () {
  50480. return this._runtimeAnimations;
  50481. },
  50482. enumerable: true,
  50483. configurable: true
  50484. });
  50485. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50486. /**
  50487. * Specifies if any of the runtime animations are currently running
  50488. */
  50489. get: function () {
  50490. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50491. var runtimeAnimation = _a[_i];
  50492. if (!runtimeAnimation.isStopped) {
  50493. return true;
  50494. }
  50495. }
  50496. return false;
  50497. },
  50498. enumerable: true,
  50499. configurable: true
  50500. });
  50501. // Methods
  50502. /**
  50503. * Converts the animation to a string
  50504. * @param fullDetails support for multiple levels of logging within scene loading
  50505. * @returns String form of the animation
  50506. */
  50507. Animation.prototype.toString = function (fullDetails) {
  50508. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50509. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50510. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50511. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50512. if (fullDetails) {
  50513. ret += ", Ranges: {";
  50514. var first = true;
  50515. for (var name in this._ranges) {
  50516. if (first) {
  50517. ret += ", ";
  50518. first = false;
  50519. }
  50520. ret += name;
  50521. }
  50522. ret += "}";
  50523. }
  50524. return ret;
  50525. };
  50526. /**
  50527. * Add an event to this animation
  50528. * @param event Event to add
  50529. */
  50530. Animation.prototype.addEvent = function (event) {
  50531. this._events.push(event);
  50532. };
  50533. /**
  50534. * Remove all events found at the given frame
  50535. * @param frame The frame to remove events from
  50536. */
  50537. Animation.prototype.removeEvents = function (frame) {
  50538. for (var index = 0; index < this._events.length; index++) {
  50539. if (this._events[index].frame === frame) {
  50540. this._events.splice(index, 1);
  50541. index--;
  50542. }
  50543. }
  50544. };
  50545. /**
  50546. * Retrieves all the events from the animation
  50547. * @returns Events from the animation
  50548. */
  50549. Animation.prototype.getEvents = function () {
  50550. return this._events;
  50551. };
  50552. /**
  50553. * Creates an animation range
  50554. * @param name Name of the animation range
  50555. * @param from Starting frame of the animation range
  50556. * @param to Ending frame of the animation
  50557. */
  50558. Animation.prototype.createRange = function (name, from, to) {
  50559. // check name not already in use; could happen for bones after serialized
  50560. if (!this._ranges[name]) {
  50561. this._ranges[name] = new AnimationRange(name, from, to);
  50562. }
  50563. };
  50564. /**
  50565. * Deletes an animation range by name
  50566. * @param name Name of the animation range to delete
  50567. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50568. */
  50569. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50570. if (deleteFrames === void 0) { deleteFrames = true; }
  50571. var range = this._ranges[name];
  50572. if (!range) {
  50573. return;
  50574. }
  50575. if (deleteFrames) {
  50576. var from = range.from;
  50577. var to = range.to;
  50578. // this loop MUST go high to low for multiple splices to work
  50579. for (var key = this._keys.length - 1; key >= 0; key--) {
  50580. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50581. this._keys.splice(key, 1);
  50582. }
  50583. }
  50584. }
  50585. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50586. };
  50587. /**
  50588. * Gets the animation range by name, or null if not defined
  50589. * @param name Name of the animation range
  50590. * @returns Nullable animation range
  50591. */
  50592. Animation.prototype.getRange = function (name) {
  50593. return this._ranges[name];
  50594. };
  50595. /**
  50596. * Gets the key frames from the animation
  50597. * @returns The key frames of the animation
  50598. */
  50599. Animation.prototype.getKeys = function () {
  50600. return this._keys;
  50601. };
  50602. /**
  50603. * Gets the highest frame rate of the animation
  50604. * @returns Highest frame rate of the animation
  50605. */
  50606. Animation.prototype.getHighestFrame = function () {
  50607. var ret = 0;
  50608. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50609. if (ret < this._keys[key].frame) {
  50610. ret = this._keys[key].frame;
  50611. }
  50612. }
  50613. return ret;
  50614. };
  50615. /**
  50616. * Gets the easing function of the animation
  50617. * @returns Easing function of the animation
  50618. */
  50619. Animation.prototype.getEasingFunction = function () {
  50620. return this._easingFunction;
  50621. };
  50622. /**
  50623. * Sets the easing function of the animation
  50624. * @param easingFunction A custom mathematical formula for animation
  50625. */
  50626. Animation.prototype.setEasingFunction = function (easingFunction) {
  50627. this._easingFunction = easingFunction;
  50628. };
  50629. /**
  50630. * Interpolates a scalar linearly
  50631. * @param startValue Start value of the animation curve
  50632. * @param endValue End value of the animation curve
  50633. * @param gradient Scalar amount to interpolate
  50634. * @returns Interpolated scalar value
  50635. */
  50636. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50637. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50638. };
  50639. /**
  50640. * Interpolates a scalar cubically
  50641. * @param startValue Start value of the animation curve
  50642. * @param outTangent End tangent of the animation
  50643. * @param endValue End value of the animation curve
  50644. * @param inTangent Start tangent of the animation curve
  50645. * @param gradient Scalar amount to interpolate
  50646. * @returns Interpolated scalar value
  50647. */
  50648. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50649. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50650. };
  50651. /**
  50652. * Interpolates a quaternion using a spherical linear interpolation
  50653. * @param startValue Start value of the animation curve
  50654. * @param endValue End value of the animation curve
  50655. * @param gradient Scalar amount to interpolate
  50656. * @returns Interpolated quaternion value
  50657. */
  50658. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50659. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50660. };
  50661. /**
  50662. * Interpolates a quaternion cubically
  50663. * @param startValue Start value of the animation curve
  50664. * @param outTangent End tangent of the animation curve
  50665. * @param endValue End value of the animation curve
  50666. * @param inTangent Start tangent of the animation curve
  50667. * @param gradient Scalar amount to interpolate
  50668. * @returns Interpolated quaternion value
  50669. */
  50670. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50671. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50672. };
  50673. /**
  50674. * Interpolates a Vector3 linearl
  50675. * @param startValue Start value of the animation curve
  50676. * @param endValue End value of the animation curve
  50677. * @param gradient Scalar amount to interpolate
  50678. * @returns Interpolated scalar value
  50679. */
  50680. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50681. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50682. };
  50683. /**
  50684. * Interpolates a Vector3 cubically
  50685. * @param startValue Start value of the animation curve
  50686. * @param outTangent End tangent of the animation
  50687. * @param endValue End value of the animation curve
  50688. * @param inTangent Start tangent of the animation curve
  50689. * @param gradient Scalar amount to interpolate
  50690. * @returns InterpolatedVector3 value
  50691. */
  50692. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50693. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50694. };
  50695. /**
  50696. * Interpolates a Vector2 linearly
  50697. * @param startValue Start value of the animation curve
  50698. * @param endValue End value of the animation curve
  50699. * @param gradient Scalar amount to interpolate
  50700. * @returns Interpolated Vector2 value
  50701. */
  50702. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50703. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50704. };
  50705. /**
  50706. * Interpolates a Vector2 cubically
  50707. * @param startValue Start value of the animation curve
  50708. * @param outTangent End tangent of the animation
  50709. * @param endValue End value of the animation curve
  50710. * @param inTangent Start tangent of the animation curve
  50711. * @param gradient Scalar amount to interpolate
  50712. * @returns Interpolated Vector2 value
  50713. */
  50714. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50715. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50716. };
  50717. /**
  50718. * Interpolates a size linearly
  50719. * @param startValue Start value of the animation curve
  50720. * @param endValue End value of the animation curve
  50721. * @param gradient Scalar amount to interpolate
  50722. * @returns Interpolated Size value
  50723. */
  50724. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50725. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50726. };
  50727. /**
  50728. * Interpolates a Color3 linearly
  50729. * @param startValue Start value of the animation curve
  50730. * @param endValue End value of the animation curve
  50731. * @param gradient Scalar amount to interpolate
  50732. * @returns Interpolated Color3 value
  50733. */
  50734. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50735. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50736. };
  50737. /**
  50738. * @hidden Internal use only
  50739. */
  50740. Animation.prototype._getKeyValue = function (value) {
  50741. if (typeof value === "function") {
  50742. return value();
  50743. }
  50744. return value;
  50745. };
  50746. /**
  50747. * @hidden Internal use only
  50748. */
  50749. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50750. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50751. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50752. }
  50753. var keys = this.getKeys();
  50754. // Try to get a hash to find the right key
  50755. 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));
  50756. if (keys[startKeyIndex].frame >= currentFrame) {
  50757. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50758. startKeyIndex--;
  50759. }
  50760. }
  50761. for (var key = startKeyIndex; key < keys.length; key++) {
  50762. var endKey = keys[key + 1];
  50763. if (endKey.frame >= currentFrame) {
  50764. var startKey = keys[key];
  50765. var startValue = this._getKeyValue(startKey.value);
  50766. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50767. return startValue;
  50768. }
  50769. var endValue = this._getKeyValue(endKey.value);
  50770. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50771. var frameDelta = endKey.frame - startKey.frame;
  50772. // gradient : percent of currentFrame between the frame inf and the frame sup
  50773. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50774. // check for easingFunction and correction of gradient
  50775. var easingFunction = this.getEasingFunction();
  50776. if (easingFunction != null) {
  50777. gradient = easingFunction.ease(gradient);
  50778. }
  50779. switch (this.dataType) {
  50780. // Float
  50781. case Animation.ANIMATIONTYPE_FLOAT:
  50782. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50783. switch (loopMode) {
  50784. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50785. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50786. return floatValue;
  50787. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50788. return offsetValue * repeatCount + floatValue;
  50789. }
  50790. break;
  50791. // Quaternion
  50792. case Animation.ANIMATIONTYPE_QUATERNION:
  50793. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50794. switch (loopMode) {
  50795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50797. return quatValue;
  50798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50799. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50800. }
  50801. return quatValue;
  50802. // Vector3
  50803. case Animation.ANIMATIONTYPE_VECTOR3:
  50804. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50805. switch (loopMode) {
  50806. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50807. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50808. return vec3Value;
  50809. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50810. return vec3Value.add(offsetValue.scale(repeatCount));
  50811. }
  50812. // Vector2
  50813. case Animation.ANIMATIONTYPE_VECTOR2:
  50814. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50815. switch (loopMode) {
  50816. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50817. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50818. return vec2Value;
  50819. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50820. return vec2Value.add(offsetValue.scale(repeatCount));
  50821. }
  50822. // Size
  50823. case Animation.ANIMATIONTYPE_SIZE:
  50824. switch (loopMode) {
  50825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50827. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50828. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50829. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50830. }
  50831. // Color3
  50832. case Animation.ANIMATIONTYPE_COLOR3:
  50833. switch (loopMode) {
  50834. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50835. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50836. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50837. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50838. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50839. }
  50840. // Matrix
  50841. case Animation.ANIMATIONTYPE_MATRIX:
  50842. switch (loopMode) {
  50843. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50844. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50845. if (Animation.AllowMatricesInterpolation) {
  50846. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50847. }
  50848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50849. return startValue;
  50850. }
  50851. default:
  50852. break;
  50853. }
  50854. break;
  50855. }
  50856. }
  50857. return this._getKeyValue(keys[keys.length - 1].value);
  50858. };
  50859. /**
  50860. * Defines the function to use to interpolate matrices
  50861. * @param startValue defines the start matrix
  50862. * @param endValue defines the end matrix
  50863. * @param gradient defines the gradient between both matrices
  50864. * @param result defines an optional target matrix where to store the interpolation
  50865. * @returns the interpolated matrix
  50866. */
  50867. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50868. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50869. if (result) {
  50870. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50871. return result;
  50872. }
  50873. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50874. }
  50875. if (result) {
  50876. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50877. return result;
  50878. }
  50879. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50880. };
  50881. /**
  50882. * Makes a copy of the animation
  50883. * @returns Cloned animation
  50884. */
  50885. Animation.prototype.clone = function () {
  50886. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50887. clone.enableBlending = this.enableBlending;
  50888. clone.blendingSpeed = this.blendingSpeed;
  50889. if (this._keys) {
  50890. clone.setKeys(this._keys);
  50891. }
  50892. if (this._ranges) {
  50893. clone._ranges = {};
  50894. for (var name in this._ranges) {
  50895. var range = this._ranges[name];
  50896. if (!range) {
  50897. continue;
  50898. }
  50899. clone._ranges[name] = range.clone();
  50900. }
  50901. }
  50902. return clone;
  50903. };
  50904. /**
  50905. * Sets the key frames of the animation
  50906. * @param values The animation key frames to set
  50907. */
  50908. Animation.prototype.setKeys = function (values) {
  50909. this._keys = values.slice(0);
  50910. };
  50911. /**
  50912. * Serializes the animation to an object
  50913. * @returns Serialized object
  50914. */
  50915. Animation.prototype.serialize = function () {
  50916. var serializationObject = {};
  50917. serializationObject.name = this.name;
  50918. serializationObject.property = this.targetProperty;
  50919. serializationObject.framePerSecond = this.framePerSecond;
  50920. serializationObject.dataType = this.dataType;
  50921. serializationObject.loopBehavior = this.loopMode;
  50922. serializationObject.enableBlending = this.enableBlending;
  50923. serializationObject.blendingSpeed = this.blendingSpeed;
  50924. var dataType = this.dataType;
  50925. serializationObject.keys = [];
  50926. var keys = this.getKeys();
  50927. for (var index = 0; index < keys.length; index++) {
  50928. var animationKey = keys[index];
  50929. var key = {};
  50930. key.frame = animationKey.frame;
  50931. switch (dataType) {
  50932. case Animation.ANIMATIONTYPE_FLOAT:
  50933. key.values = [animationKey.value];
  50934. break;
  50935. case Animation.ANIMATIONTYPE_QUATERNION:
  50936. case Animation.ANIMATIONTYPE_MATRIX:
  50937. case Animation.ANIMATIONTYPE_VECTOR3:
  50938. case Animation.ANIMATIONTYPE_COLOR3:
  50939. key.values = animationKey.value.asArray();
  50940. break;
  50941. }
  50942. serializationObject.keys.push(key);
  50943. }
  50944. serializationObject.ranges = [];
  50945. for (var name in this._ranges) {
  50946. var source = this._ranges[name];
  50947. if (!source) {
  50948. continue;
  50949. }
  50950. var range = {};
  50951. range.name = name;
  50952. range.from = source.from;
  50953. range.to = source.to;
  50954. serializationObject.ranges.push(range);
  50955. }
  50956. return serializationObject;
  50957. };
  50958. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50959. /**
  50960. * Get the float animation type
  50961. */
  50962. get: function () {
  50963. return Animation._ANIMATIONTYPE_FLOAT;
  50964. },
  50965. enumerable: true,
  50966. configurable: true
  50967. });
  50968. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50969. /**
  50970. * Get the Vector3 animation type
  50971. */
  50972. get: function () {
  50973. return Animation._ANIMATIONTYPE_VECTOR3;
  50974. },
  50975. enumerable: true,
  50976. configurable: true
  50977. });
  50978. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50979. /**
  50980. * Get the Vectpr2 animation type
  50981. */
  50982. get: function () {
  50983. return Animation._ANIMATIONTYPE_VECTOR2;
  50984. },
  50985. enumerable: true,
  50986. configurable: true
  50987. });
  50988. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50989. /**
  50990. * Get the Size animation type
  50991. */
  50992. get: function () {
  50993. return Animation._ANIMATIONTYPE_SIZE;
  50994. },
  50995. enumerable: true,
  50996. configurable: true
  50997. });
  50998. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50999. /**
  51000. * Get the Quaternion animation type
  51001. */
  51002. get: function () {
  51003. return Animation._ANIMATIONTYPE_QUATERNION;
  51004. },
  51005. enumerable: true,
  51006. configurable: true
  51007. });
  51008. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51009. /**
  51010. * Get the Matrix animation type
  51011. */
  51012. get: function () {
  51013. return Animation._ANIMATIONTYPE_MATRIX;
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51019. /**
  51020. * Get the Color3 animation type
  51021. */
  51022. get: function () {
  51023. return Animation._ANIMATIONTYPE_COLOR3;
  51024. },
  51025. enumerable: true,
  51026. configurable: true
  51027. });
  51028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51029. /**
  51030. * Get the Relative Loop Mode
  51031. */
  51032. get: function () {
  51033. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51034. },
  51035. enumerable: true,
  51036. configurable: true
  51037. });
  51038. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51039. /**
  51040. * Get the Cycle Loop Mode
  51041. */
  51042. get: function () {
  51043. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51044. },
  51045. enumerable: true,
  51046. configurable: true
  51047. });
  51048. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51049. /**
  51050. * Get the Constant Loop Mode
  51051. */
  51052. get: function () {
  51053. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51054. },
  51055. enumerable: true,
  51056. configurable: true
  51057. });
  51058. /** @ignore */
  51059. Animation._UniversalLerp = function (left, right, amount) {
  51060. var constructor = left.constructor;
  51061. if (constructor.Lerp) { // Lerp supported
  51062. return constructor.Lerp(left, right, amount);
  51063. }
  51064. else if (constructor.Slerp) { // Slerp supported
  51065. return constructor.Slerp(left, right, amount);
  51066. }
  51067. else if (left.toFixed) { // Number
  51068. return left * (1.0 - amount) + amount * right;
  51069. }
  51070. else { // Blending not supported
  51071. return right;
  51072. }
  51073. };
  51074. /**
  51075. * Parses an animation object and creates an animation
  51076. * @param parsedAnimation Parsed animation object
  51077. * @returns Animation object
  51078. */
  51079. Animation.Parse = function (parsedAnimation) {
  51080. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51081. var dataType = parsedAnimation.dataType;
  51082. var keys = [];
  51083. var data;
  51084. var index;
  51085. if (parsedAnimation.enableBlending) {
  51086. animation.enableBlending = parsedAnimation.enableBlending;
  51087. }
  51088. if (parsedAnimation.blendingSpeed) {
  51089. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51090. }
  51091. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51092. var key = parsedAnimation.keys[index];
  51093. var inTangent;
  51094. var outTangent;
  51095. switch (dataType) {
  51096. case Animation.ANIMATIONTYPE_FLOAT:
  51097. data = key.values[0];
  51098. if (key.values.length >= 1) {
  51099. inTangent = key.values[1];
  51100. }
  51101. if (key.values.length >= 2) {
  51102. outTangent = key.values[2];
  51103. }
  51104. break;
  51105. case Animation.ANIMATIONTYPE_QUATERNION:
  51106. data = BABYLON.Quaternion.FromArray(key.values);
  51107. if (key.values.length >= 8) {
  51108. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51109. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51110. inTangent = _inTangent;
  51111. }
  51112. }
  51113. if (key.values.length >= 12) {
  51114. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51115. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51116. outTangent = _outTangent;
  51117. }
  51118. }
  51119. break;
  51120. case Animation.ANIMATIONTYPE_MATRIX:
  51121. data = BABYLON.Matrix.FromArray(key.values);
  51122. break;
  51123. case Animation.ANIMATIONTYPE_COLOR3:
  51124. data = BABYLON.Color3.FromArray(key.values);
  51125. break;
  51126. case Animation.ANIMATIONTYPE_VECTOR3:
  51127. default:
  51128. data = BABYLON.Vector3.FromArray(key.values);
  51129. break;
  51130. }
  51131. var keyData = {};
  51132. keyData.frame = key.frame;
  51133. keyData.value = data;
  51134. if (inTangent != undefined) {
  51135. keyData.inTangent = inTangent;
  51136. }
  51137. if (outTangent != undefined) {
  51138. keyData.outTangent = outTangent;
  51139. }
  51140. keys.push(keyData);
  51141. }
  51142. animation.setKeys(keys);
  51143. if (parsedAnimation.ranges) {
  51144. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51145. data = parsedAnimation.ranges[index];
  51146. animation.createRange(data.name, data.from, data.to);
  51147. }
  51148. }
  51149. return animation;
  51150. };
  51151. /**
  51152. * Appends the serialized animations from the source animations
  51153. * @param source Source containing the animations
  51154. * @param destination Target to store the animations
  51155. */
  51156. Animation.AppendSerializedAnimations = function (source, destination) {
  51157. if (source.animations) {
  51158. destination.animations = [];
  51159. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51160. var animation = source.animations[animationIndex];
  51161. destination.animations.push(animation.serialize());
  51162. }
  51163. }
  51164. };
  51165. /**
  51166. * Use matrix interpolation instead of using direct key value when animating matrices
  51167. */
  51168. Animation.AllowMatricesInterpolation = false;
  51169. /**
  51170. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51171. */
  51172. Animation.AllowMatrixDecomposeForInterpolation = true;
  51173. // Statics
  51174. /**
  51175. * Float animation type
  51176. */
  51177. Animation._ANIMATIONTYPE_FLOAT = 0;
  51178. /**
  51179. * Vector3 animation type
  51180. */
  51181. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51182. /**
  51183. * Quaternion animation type
  51184. */
  51185. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51186. /**
  51187. * Matrix animation type
  51188. */
  51189. Animation._ANIMATIONTYPE_MATRIX = 3;
  51190. /**
  51191. * Color3 animation type
  51192. */
  51193. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51194. /**
  51195. * Vector2 animation type
  51196. */
  51197. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51198. /**
  51199. * Size animation type
  51200. */
  51201. Animation._ANIMATIONTYPE_SIZE = 6;
  51202. /**
  51203. * Relative Loop Mode
  51204. */
  51205. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51206. /**
  51207. * Cycle Loop Mode
  51208. */
  51209. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51210. /**
  51211. * Constant Loop Mode
  51212. */
  51213. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51214. return Animation;
  51215. }());
  51216. BABYLON.Animation = Animation;
  51217. })(BABYLON || (BABYLON = {}));
  51218. //# sourceMappingURL=babylon.animation.js.map
  51219. var BABYLON;
  51220. (function (BABYLON) {
  51221. /**
  51222. * This class defines the direct association between an animation and a target
  51223. */
  51224. var TargetedAnimation = /** @class */ (function () {
  51225. function TargetedAnimation() {
  51226. }
  51227. return TargetedAnimation;
  51228. }());
  51229. BABYLON.TargetedAnimation = TargetedAnimation;
  51230. /**
  51231. * Use this class to create coordinated animations on multiple targets
  51232. */
  51233. var AnimationGroup = /** @class */ (function () {
  51234. function AnimationGroup(name, scene) {
  51235. if (scene === void 0) { scene = null; }
  51236. this.name = name;
  51237. this._targetedAnimations = new Array();
  51238. this._animatables = new Array();
  51239. this._from = Number.MAX_VALUE;
  51240. this._to = -Number.MAX_VALUE;
  51241. this._speedRatio = 1;
  51242. this.onAnimationEndObservable = new BABYLON.Observable();
  51243. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51244. this._scene.animationGroups.push(this);
  51245. }
  51246. Object.defineProperty(AnimationGroup.prototype, "from", {
  51247. /**
  51248. * Gets the first frame
  51249. */
  51250. get: function () {
  51251. return this._from;
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. Object.defineProperty(AnimationGroup.prototype, "to", {
  51257. /**
  51258. * Gets the last frame
  51259. */
  51260. get: function () {
  51261. return this._to;
  51262. },
  51263. enumerable: true,
  51264. configurable: true
  51265. });
  51266. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51267. /**
  51268. * Define if the animations are started
  51269. */
  51270. get: function () {
  51271. return this._isStarted;
  51272. },
  51273. enumerable: true,
  51274. configurable: true
  51275. });
  51276. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51277. /**
  51278. * Gets or sets the speed ratio to use for all animations
  51279. */
  51280. get: function () {
  51281. return this._speedRatio;
  51282. },
  51283. /**
  51284. * Gets or sets the speed ratio to use for all animations
  51285. */
  51286. set: function (value) {
  51287. if (this._speedRatio === value) {
  51288. return;
  51289. }
  51290. this._speedRatio = value;
  51291. for (var index = 0; index < this._animatables.length; index++) {
  51292. var animatable = this._animatables[index];
  51293. animatable.speedRatio = this._speedRatio;
  51294. }
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51300. /**
  51301. * Gets the targeted animations for this animation group
  51302. */
  51303. get: function () {
  51304. return this._targetedAnimations;
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51310. /**
  51311. * returning the list of animatables controlled by this animation group.
  51312. */
  51313. get: function () {
  51314. return this._animatables;
  51315. },
  51316. enumerable: true,
  51317. configurable: true
  51318. });
  51319. /**
  51320. * Add an animation (with its target) in the group
  51321. * @param animation defines the animation we want to add
  51322. * @param target defines the target of the animation
  51323. * @returns the {BABYLON.TargetedAnimation} object
  51324. */
  51325. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51326. var targetedAnimation = {
  51327. animation: animation,
  51328. target: target
  51329. };
  51330. var keys = animation.getKeys();
  51331. if (this._from > keys[0].frame) {
  51332. this._from = keys[0].frame;
  51333. }
  51334. if (this._to < keys[keys.length - 1].frame) {
  51335. this._to = keys[keys.length - 1].frame;
  51336. }
  51337. this._targetedAnimations.push(targetedAnimation);
  51338. return targetedAnimation;
  51339. };
  51340. /**
  51341. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51342. * It can add constant keys at begin or end
  51343. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51344. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51345. */
  51346. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51347. if (beginFrame === void 0) { beginFrame = null; }
  51348. if (endFrame === void 0) { endFrame = null; }
  51349. if (beginFrame == null)
  51350. beginFrame = this._from;
  51351. if (endFrame == null)
  51352. endFrame = this._to;
  51353. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51354. var targetedAnimation = this._targetedAnimations[index];
  51355. var keys = targetedAnimation.animation.getKeys();
  51356. var startKey = keys[0];
  51357. var endKey = keys[keys.length - 1];
  51358. if (startKey.frame > beginFrame) {
  51359. var newKey = {
  51360. frame: beginFrame,
  51361. value: startKey.value,
  51362. inTangent: startKey.inTangent,
  51363. outTangent: startKey.outTangent,
  51364. interpolation: startKey.interpolation
  51365. };
  51366. keys.splice(0, 0, newKey);
  51367. }
  51368. if (endKey.frame < endFrame) {
  51369. var newKey = {
  51370. frame: endFrame,
  51371. value: endKey.value,
  51372. inTangent: endKey.outTangent,
  51373. outTangent: endKey.outTangent,
  51374. interpolation: endKey.interpolation
  51375. };
  51376. keys.push(newKey);
  51377. }
  51378. }
  51379. this._from = beginFrame;
  51380. this._to = endFrame;
  51381. return this;
  51382. };
  51383. /**
  51384. * Start all animations on given targets
  51385. * @param loop defines if animations must loop
  51386. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51387. * @param from defines the from key (optional)
  51388. * @param to defines the to key (optional)
  51389. * @returns the current animation group
  51390. */
  51391. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51392. var _this = this;
  51393. if (loop === void 0) { loop = false; }
  51394. if (speedRatio === void 0) { speedRatio = 1; }
  51395. if (this._isStarted || this._targetedAnimations.length === 0) {
  51396. return this;
  51397. }
  51398. var _loop_1 = function (targetedAnimation) {
  51399. 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 () {
  51400. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51401. }));
  51402. };
  51403. var this_1 = this;
  51404. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51405. var targetedAnimation = _a[_i];
  51406. _loop_1(targetedAnimation);
  51407. }
  51408. this._speedRatio = speedRatio;
  51409. this._isStarted = true;
  51410. return this;
  51411. };
  51412. /**
  51413. * Pause all animations
  51414. */
  51415. AnimationGroup.prototype.pause = function () {
  51416. if (!this._isStarted) {
  51417. return this;
  51418. }
  51419. for (var index = 0; index < this._animatables.length; index++) {
  51420. var animatable = this._animatables[index];
  51421. animatable.pause();
  51422. }
  51423. return this;
  51424. };
  51425. /**
  51426. * Play all animations to initial state
  51427. * This function will start() the animations if they were not started or will restart() them if they were paused
  51428. * @param loop defines if animations must loop
  51429. */
  51430. AnimationGroup.prototype.play = function (loop) {
  51431. if (this.isStarted) {
  51432. if (loop !== undefined) {
  51433. for (var index = 0; index < this._animatables.length; index++) {
  51434. var animatable = this._animatables[index];
  51435. animatable.loopAnimation = loop;
  51436. }
  51437. }
  51438. this.restart();
  51439. }
  51440. else {
  51441. this.start(loop, this._speedRatio);
  51442. }
  51443. return this;
  51444. };
  51445. /**
  51446. * Reset all animations to initial state
  51447. */
  51448. AnimationGroup.prototype.reset = function () {
  51449. if (!this._isStarted) {
  51450. return this;
  51451. }
  51452. for (var index = 0; index < this._animatables.length; index++) {
  51453. var animatable = this._animatables[index];
  51454. animatable.reset();
  51455. }
  51456. return this;
  51457. };
  51458. /**
  51459. * Restart animations from key 0
  51460. */
  51461. AnimationGroup.prototype.restart = function () {
  51462. if (!this._isStarted) {
  51463. return this;
  51464. }
  51465. for (var index = 0; index < this._animatables.length; index++) {
  51466. var animatable = this._animatables[index];
  51467. animatable.restart();
  51468. }
  51469. return this;
  51470. };
  51471. /**
  51472. * Stop all animations
  51473. */
  51474. AnimationGroup.prototype.stop = function () {
  51475. if (!this._isStarted) {
  51476. return this;
  51477. }
  51478. for (var index = 0; index < this._animatables.length; index++) {
  51479. var animatable = this._animatables[index];
  51480. animatable.stop();
  51481. }
  51482. this._isStarted = false;
  51483. return this;
  51484. };
  51485. /**
  51486. * Set animation weight for all animatables
  51487. * @param weight defines the weight to use
  51488. * @return the animationGroup
  51489. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51490. */
  51491. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51492. for (var index = 0; index < this._animatables.length; index++) {
  51493. var animatable = this._animatables[index];
  51494. animatable.weight = weight;
  51495. }
  51496. return this;
  51497. };
  51498. /**
  51499. * Synchronize and normalize all animatables with a source animatable
  51500. * @param root defines the root animatable to synchronize with
  51501. * @return the animationGroup
  51502. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51503. */
  51504. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51505. for (var index = 0; index < this._animatables.length; index++) {
  51506. var animatable = this._animatables[index];
  51507. animatable.syncWith(root);
  51508. }
  51509. return this;
  51510. };
  51511. /**
  51512. * Goes to a specific frame in this animation group
  51513. * @param frame the frame number to go to
  51514. * @return the animationGroup
  51515. */
  51516. AnimationGroup.prototype.goToFrame = function (frame) {
  51517. if (!this._isStarted) {
  51518. return this;
  51519. }
  51520. for (var index = 0; index < this._animatables.length; index++) {
  51521. var animatable = this._animatables[index];
  51522. animatable.goToFrame(frame);
  51523. }
  51524. return this;
  51525. };
  51526. /**
  51527. * Dispose all associated resources
  51528. */
  51529. AnimationGroup.prototype.dispose = function () {
  51530. this._targetedAnimations = [];
  51531. this._animatables = [];
  51532. var index = this._scene.animationGroups.indexOf(this);
  51533. if (index > -1) {
  51534. this._scene.animationGroups.splice(index, 1);
  51535. }
  51536. };
  51537. return AnimationGroup;
  51538. }());
  51539. BABYLON.AnimationGroup = AnimationGroup;
  51540. })(BABYLON || (BABYLON = {}));
  51541. //# sourceMappingURL=babylon.animationGroup.js.map
  51542. var BABYLON;
  51543. (function (BABYLON) {
  51544. /**
  51545. * Defines a runtime animation
  51546. */
  51547. var RuntimeAnimation = /** @class */ (function () {
  51548. /**
  51549. * Create a new RuntimeAnimation object
  51550. * @param target defines the target of the animation
  51551. * @param animation defines the source animation object
  51552. * @param scene defines the hosting scene
  51553. * @param host defines the initiating Animatable
  51554. */
  51555. function RuntimeAnimation(target, animation, scene, host) {
  51556. /**
  51557. * The current frame of the runtime animation
  51558. */
  51559. this._currentFrame = 0;
  51560. /**
  51561. * The original value of the runtime animation
  51562. */
  51563. this._originalValue = new Array();
  51564. /**
  51565. * The offsets cache of the runtime animation
  51566. */
  51567. this._offsetsCache = {};
  51568. /**
  51569. * The high limits cache of the runtime animation
  51570. */
  51571. this._highLimitsCache = {};
  51572. /**
  51573. * Specifies if the runtime animation has been stopped
  51574. */
  51575. this._stopped = false;
  51576. /**
  51577. * The blending factor of the runtime animation
  51578. */
  51579. this._blendingFactor = 0;
  51580. /**
  51581. * The target path of the runtime animation
  51582. */
  51583. this._targetPath = "";
  51584. /**
  51585. * The weight of the runtime animation
  51586. */
  51587. this._weight = 1.0;
  51588. /**
  51589. * The ratio offset of the runtime animation
  51590. */
  51591. this._ratioOffset = 0;
  51592. /**
  51593. * The previous delay of the runtime animation
  51594. */
  51595. this._previousDelay = 0;
  51596. /**
  51597. * The previous ratio of the runtime animation
  51598. */
  51599. this._previousRatio = 0;
  51600. this._animation = animation;
  51601. this._target = target;
  51602. this._scene = scene;
  51603. this._host = host;
  51604. animation._runtimeAnimations.push(this);
  51605. }
  51606. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51607. /**
  51608. * Gets the current frame of the runtime animation
  51609. */
  51610. get: function () {
  51611. return this._currentFrame;
  51612. },
  51613. enumerable: true,
  51614. configurable: true
  51615. });
  51616. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51617. /**
  51618. * Gets the weight of the runtime animation
  51619. */
  51620. get: function () {
  51621. return this._weight;
  51622. },
  51623. enumerable: true,
  51624. configurable: true
  51625. });
  51626. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51627. /**
  51628. * Gets the current value of the runtime animation
  51629. */
  51630. get: function () {
  51631. return this._currentValue;
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51637. /**
  51638. * Gets the target path of the runtime animation
  51639. */
  51640. get: function () {
  51641. return this._targetPath;
  51642. },
  51643. enumerable: true,
  51644. configurable: true
  51645. });
  51646. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51647. /**
  51648. * Gets the actual target of the runtime animation
  51649. */
  51650. get: function () {
  51651. return this._activeTarget;
  51652. },
  51653. enumerable: true,
  51654. configurable: true
  51655. });
  51656. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51657. /**
  51658. * Gets the animation from the runtime animation
  51659. */
  51660. get: function () {
  51661. return this._animation;
  51662. },
  51663. enumerable: true,
  51664. configurable: true
  51665. });
  51666. /**
  51667. * Resets the runtime animation to the beginning
  51668. * @param restoreOriginal defines whether to restore the target property to the original value
  51669. */
  51670. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51671. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51672. if (restoreOriginal) {
  51673. if (this._target instanceof Array) {
  51674. var index = 0;
  51675. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51676. var target = _a[_i];
  51677. if (this._originalValue[index] !== undefined) {
  51678. this._setValue(target, this._originalValue[index], -1);
  51679. }
  51680. index++;
  51681. }
  51682. }
  51683. else {
  51684. if (this._originalValue[0] !== undefined) {
  51685. this._setValue(this._target, this._originalValue[0], -1);
  51686. }
  51687. }
  51688. }
  51689. this._offsetsCache = {};
  51690. this._highLimitsCache = {};
  51691. this._currentFrame = 0;
  51692. this._blendingFactor = 0;
  51693. this._originalValue = new Array();
  51694. };
  51695. /**
  51696. * Specifies if the runtime animation is stopped
  51697. * @returns Boolean specifying if the runtime animation is stopped
  51698. */
  51699. RuntimeAnimation.prototype.isStopped = function () {
  51700. return this._stopped;
  51701. };
  51702. /**
  51703. * Disposes of the runtime animation
  51704. */
  51705. RuntimeAnimation.prototype.dispose = function () {
  51706. var index = this._animation.runtimeAnimations.indexOf(this);
  51707. if (index > -1) {
  51708. this._animation.runtimeAnimations.splice(index, 1);
  51709. }
  51710. };
  51711. /**
  51712. * Interpolates the animation from the current frame
  51713. * @param currentFrame The frame to interpolate the animation to
  51714. * @param repeatCount The number of times that the animation should loop
  51715. * @param loopMode The type of looping mode to use
  51716. * @param offsetValue Animation offset value
  51717. * @param highLimitValue The high limit value
  51718. * @returns The interpolated value
  51719. */
  51720. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51721. this._currentFrame = currentFrame;
  51722. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51723. this._workValue = BABYLON.Matrix.Zero();
  51724. }
  51725. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51726. };
  51727. /**
  51728. * Apply the interpolated value to the target
  51729. * @param currentValue defines the value computed by the animation
  51730. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51731. */
  51732. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51733. if (weight === void 0) { weight = 1.0; }
  51734. if (this._target instanceof Array) {
  51735. var index = 0;
  51736. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51737. var target = _a[_i];
  51738. this._setValue(target, currentValue, weight, index);
  51739. index++;
  51740. }
  51741. }
  51742. else {
  51743. this._setValue(this._target, currentValue, weight);
  51744. }
  51745. };
  51746. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51747. if (targetIndex === void 0) { targetIndex = 0; }
  51748. // Set value
  51749. var path;
  51750. var destination;
  51751. var targetPropertyPath = this._animation.targetPropertyPath;
  51752. if (targetPropertyPath.length > 1) {
  51753. var property = target[targetPropertyPath[0]];
  51754. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51755. property = property[targetPropertyPath[index]];
  51756. }
  51757. path = targetPropertyPath[targetPropertyPath.length - 1];
  51758. destination = property;
  51759. }
  51760. else {
  51761. path = targetPropertyPath[0];
  51762. destination = target;
  51763. }
  51764. this._targetPath = path;
  51765. this._activeTarget = destination;
  51766. this._weight = weight;
  51767. if (this._originalValue[targetIndex] === undefined) {
  51768. var originalValue = void 0;
  51769. if (destination.getRestPose && path === "_matrix") { // For bones
  51770. originalValue = destination.getRestPose();
  51771. }
  51772. else {
  51773. originalValue = destination[path];
  51774. }
  51775. if (originalValue && originalValue.clone) {
  51776. this._originalValue[targetIndex] = originalValue.clone();
  51777. }
  51778. else {
  51779. this._originalValue[targetIndex] = originalValue;
  51780. }
  51781. }
  51782. // Blending
  51783. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51784. if (enableBlending && this._blendingFactor <= 1.0) {
  51785. if (!this._originalBlendValue) {
  51786. var originalValue = destination[path];
  51787. if (originalValue.clone) {
  51788. this._originalBlendValue = originalValue.clone();
  51789. }
  51790. else {
  51791. this._originalBlendValue = originalValue;
  51792. }
  51793. }
  51794. if (this._originalBlendValue.m) { // Matrix
  51795. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51796. if (this._currentValue) {
  51797. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51798. }
  51799. else {
  51800. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51801. }
  51802. }
  51803. else {
  51804. if (this._currentValue) {
  51805. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51806. }
  51807. else {
  51808. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51809. }
  51810. }
  51811. }
  51812. else {
  51813. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51814. }
  51815. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51816. this._blendingFactor += blendingSpeed;
  51817. }
  51818. else {
  51819. this._currentValue = currentValue;
  51820. }
  51821. if (weight !== -1.0) {
  51822. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51823. }
  51824. else {
  51825. destination[path] = this._currentValue;
  51826. }
  51827. if (target.markAsDirty) {
  51828. target.markAsDirty(this._animation.targetProperty);
  51829. }
  51830. };
  51831. /**
  51832. * Gets the loop pmode of the runtime animation
  51833. * @returns Loop Mode
  51834. */
  51835. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51836. if (this._target && this._target.animationPropertiesOverride) {
  51837. return this._target.animationPropertiesOverride.loopMode;
  51838. }
  51839. return this._animation.loopMode;
  51840. };
  51841. /**
  51842. * Move the current animation to a given frame
  51843. * @param frame defines the frame to move to
  51844. */
  51845. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51846. var keys = this._animation.getKeys();
  51847. if (frame < keys[0].frame) {
  51848. frame = keys[0].frame;
  51849. }
  51850. else if (frame > keys[keys.length - 1].frame) {
  51851. frame = keys[keys.length - 1].frame;
  51852. }
  51853. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51854. this.setValue(currentValue, -1);
  51855. };
  51856. /**
  51857. * @hidden Internal use only
  51858. */
  51859. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51860. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51861. this._ratioOffset = this._previousRatio - newRatio;
  51862. };
  51863. /**
  51864. * Execute the current animation
  51865. * @param delay defines the delay to add to the current frame
  51866. * @param from defines the lower bound of the animation range
  51867. * @param to defines the upper bound of the animation range
  51868. * @param loop defines if the current animation must loop
  51869. * @param speedRatio defines the current speed ratio
  51870. * @param weight defines the weight of the animation (default is -1 so no weight)
  51871. * @returns a boolean indicating if the animation has ended
  51872. */
  51873. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51874. if (weight === void 0) { weight = -1.0; }
  51875. var targetPropertyPath = this._animation.targetPropertyPath;
  51876. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51877. this._stopped = true;
  51878. return false;
  51879. }
  51880. var returnValue = true;
  51881. var keys = this._animation.getKeys();
  51882. // Adding a start key at frame 0 if missing
  51883. if (keys[0].frame !== 0) {
  51884. var newKey = { frame: 0, value: keys[0].value };
  51885. keys.splice(0, 0, newKey);
  51886. }
  51887. // Check limits
  51888. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51889. from = keys[0].frame;
  51890. }
  51891. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51892. to = keys[keys.length - 1].frame;
  51893. }
  51894. //to and from cannot be the same key
  51895. if (from === to) {
  51896. if (from > keys[0].frame) {
  51897. from--;
  51898. }
  51899. else if (to < keys[keys.length - 1].frame) {
  51900. to++;
  51901. }
  51902. }
  51903. // Compute ratio
  51904. var range = to - from;
  51905. var offsetValue;
  51906. // ratio represents the frame delta between from and to
  51907. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51908. var highLimitValue = 0;
  51909. this._previousDelay = delay;
  51910. this._previousRatio = ratio;
  51911. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51912. returnValue = false;
  51913. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51914. }
  51915. else {
  51916. // Get max value if required
  51917. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51918. var keyOffset = to.toString() + from.toString();
  51919. if (!this._offsetsCache[keyOffset]) {
  51920. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51921. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51922. switch (this._animation.dataType) {
  51923. // Float
  51924. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51925. this._offsetsCache[keyOffset] = toValue - fromValue;
  51926. break;
  51927. // Quaternion
  51928. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51930. break;
  51931. // Vector3
  51932. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51933. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51934. // Vector2
  51935. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51936. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51937. // Size
  51938. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51939. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51940. // Color3
  51941. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51942. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51943. default:
  51944. break;
  51945. }
  51946. this._highLimitsCache[keyOffset] = toValue;
  51947. }
  51948. highLimitValue = this._highLimitsCache[keyOffset];
  51949. offsetValue = this._offsetsCache[keyOffset];
  51950. }
  51951. }
  51952. if (offsetValue === undefined) {
  51953. switch (this._animation.dataType) {
  51954. // Float
  51955. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51956. offsetValue = 0;
  51957. break;
  51958. // Quaternion
  51959. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51960. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51961. break;
  51962. // Vector3
  51963. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51964. offsetValue = BABYLON.Vector3.Zero();
  51965. break;
  51966. // Vector2
  51967. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51968. offsetValue = BABYLON.Vector2.Zero();
  51969. break;
  51970. // Size
  51971. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51972. offsetValue = BABYLON.Size.Zero();
  51973. break;
  51974. // Color3
  51975. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51976. offsetValue = BABYLON.Color3.Black();
  51977. }
  51978. }
  51979. // Compute value
  51980. var repeatCount = (ratio / range) >> 0;
  51981. var currentFrame = returnValue ? from + ratio % range : to;
  51982. // Need to normalize?
  51983. if (this._host && this._host.syncRoot) {
  51984. var syncRoot = this._host.syncRoot;
  51985. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51986. currentFrame = from + (to - from) * hostNormalizedFrame;
  51987. }
  51988. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51989. // Set value
  51990. this.setValue(currentValue, weight);
  51991. // Check events
  51992. var events = this._animation.getEvents();
  51993. for (var index = 0; index < events.length; index++) {
  51994. // Make sure current frame has passed event frame and that event frame is within the current range
  51995. // Also, handle both forward and reverse animations
  51996. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51997. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51998. var event = events[index];
  51999. if (!event.isDone) {
  52000. // If event should be done only once, remove it.
  52001. if (event.onlyOnce) {
  52002. events.splice(index, 1);
  52003. index--;
  52004. }
  52005. event.isDone = true;
  52006. event.action();
  52007. } // Don't do anything if the event has already be done.
  52008. }
  52009. else if (events[index].isDone && !events[index].onlyOnce) {
  52010. // reset event, the animation is looping
  52011. events[index].isDone = false;
  52012. }
  52013. }
  52014. if (!returnValue) {
  52015. this._stopped = true;
  52016. }
  52017. return returnValue;
  52018. };
  52019. return RuntimeAnimation;
  52020. }());
  52021. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52022. })(BABYLON || (BABYLON = {}));
  52023. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52024. var BABYLON;
  52025. (function (BABYLON) {
  52026. var Animatable = /** @class */ (function () {
  52027. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52028. if (fromFrame === void 0) { fromFrame = 0; }
  52029. if (toFrame === void 0) { toFrame = 100; }
  52030. if (loopAnimation === void 0) { loopAnimation = false; }
  52031. if (speedRatio === void 0) { speedRatio = 1.0; }
  52032. this.target = target;
  52033. this.fromFrame = fromFrame;
  52034. this.toFrame = toFrame;
  52035. this.loopAnimation = loopAnimation;
  52036. this.onAnimationEnd = onAnimationEnd;
  52037. this._localDelayOffset = null;
  52038. this._pausedDelay = null;
  52039. this._runtimeAnimations = new Array();
  52040. this._paused = false;
  52041. this._speedRatio = 1;
  52042. this._weight = -1.0;
  52043. this.animationStarted = false;
  52044. this._scene = scene;
  52045. if (animations) {
  52046. this.appendAnimations(target, animations);
  52047. }
  52048. this._speedRatio = speedRatio;
  52049. scene._activeAnimatables.push(this);
  52050. }
  52051. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52052. /**
  52053. * Gets the root Animatable used to synchronize and normalize animations
  52054. */
  52055. get: function () {
  52056. return this._syncRoot;
  52057. },
  52058. enumerable: true,
  52059. configurable: true
  52060. });
  52061. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52062. /**
  52063. * Gets the current frame of the first RuntimeAnimation
  52064. * Used to synchronize Animatables
  52065. */
  52066. get: function () {
  52067. if (this._runtimeAnimations.length === 0) {
  52068. return 0;
  52069. }
  52070. return this._runtimeAnimations[0].currentFrame;
  52071. },
  52072. enumerable: true,
  52073. configurable: true
  52074. });
  52075. Object.defineProperty(Animatable.prototype, "weight", {
  52076. /**
  52077. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52078. */
  52079. get: function () {
  52080. return this._weight;
  52081. },
  52082. set: function (value) {
  52083. if (value === -1) { // -1 is ok and means no weight
  52084. this._weight = -1;
  52085. return;
  52086. }
  52087. // Else weight must be in [0, 1] range
  52088. this._weight = Math.min(Math.max(value, 0), 1.0);
  52089. },
  52090. enumerable: true,
  52091. configurable: true
  52092. });
  52093. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52094. /**
  52095. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52096. */
  52097. get: function () {
  52098. return this._speedRatio;
  52099. },
  52100. set: function (value) {
  52101. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52102. var animation = this._runtimeAnimations[index];
  52103. animation._prepareForSpeedRatioChange(value);
  52104. }
  52105. this._speedRatio = value;
  52106. },
  52107. enumerable: true,
  52108. configurable: true
  52109. });
  52110. // Methods
  52111. /**
  52112. * Synchronize and normalize current Animatable with a source Animatable
  52113. * This is useful when using animation weights and when animations are not of the same length
  52114. * @param root defines the root Animatable to synchronize with
  52115. * @returns the current Animatable
  52116. */
  52117. Animatable.prototype.syncWith = function (root) {
  52118. this._syncRoot = root;
  52119. if (root) {
  52120. // Make sure this animatable will animate after the root
  52121. var index = this._scene._activeAnimatables.indexOf(this);
  52122. if (index > -1) {
  52123. this._scene._activeAnimatables.splice(index, 1);
  52124. this._scene._activeAnimatables.push(this);
  52125. }
  52126. }
  52127. return this;
  52128. };
  52129. Animatable.prototype.getAnimations = function () {
  52130. return this._runtimeAnimations;
  52131. };
  52132. Animatable.prototype.appendAnimations = function (target, animations) {
  52133. for (var index = 0; index < animations.length; index++) {
  52134. var animation = animations[index];
  52135. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52136. }
  52137. };
  52138. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52139. var runtimeAnimations = this._runtimeAnimations;
  52140. for (var index = 0; index < runtimeAnimations.length; index++) {
  52141. if (runtimeAnimations[index].animation.targetProperty === property) {
  52142. return runtimeAnimations[index].animation;
  52143. }
  52144. }
  52145. return null;
  52146. };
  52147. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52148. var runtimeAnimations = this._runtimeAnimations;
  52149. for (var index = 0; index < runtimeAnimations.length; index++) {
  52150. if (runtimeAnimations[index].animation.targetProperty === property) {
  52151. return runtimeAnimations[index];
  52152. }
  52153. }
  52154. return null;
  52155. };
  52156. Animatable.prototype.reset = function () {
  52157. var runtimeAnimations = this._runtimeAnimations;
  52158. for (var index = 0; index < runtimeAnimations.length; index++) {
  52159. runtimeAnimations[index].reset(true);
  52160. }
  52161. this._localDelayOffset = null;
  52162. this._pausedDelay = null;
  52163. };
  52164. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52165. var runtimeAnimations = this._runtimeAnimations;
  52166. for (var index = 0; index < runtimeAnimations.length; index++) {
  52167. runtimeAnimations[index].animation.enableBlending = true;
  52168. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52169. }
  52170. };
  52171. Animatable.prototype.disableBlending = function () {
  52172. var runtimeAnimations = this._runtimeAnimations;
  52173. for (var index = 0; index < runtimeAnimations.length; index++) {
  52174. runtimeAnimations[index].animation.enableBlending = false;
  52175. }
  52176. };
  52177. Animatable.prototype.goToFrame = function (frame) {
  52178. var runtimeAnimations = this._runtimeAnimations;
  52179. if (runtimeAnimations[0]) {
  52180. var fps = runtimeAnimations[0].animation.framePerSecond;
  52181. var currentFrame = runtimeAnimations[0].currentFrame;
  52182. var adjustTime = frame - currentFrame;
  52183. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52184. if (this._localDelayOffset === null) {
  52185. this._localDelayOffset = 0;
  52186. }
  52187. this._localDelayOffset -= delay;
  52188. }
  52189. for (var index = 0; index < runtimeAnimations.length; index++) {
  52190. runtimeAnimations[index].goToFrame(frame);
  52191. }
  52192. };
  52193. Animatable.prototype.pause = function () {
  52194. if (this._paused) {
  52195. return;
  52196. }
  52197. this._paused = true;
  52198. };
  52199. Animatable.prototype.restart = function () {
  52200. this._paused = false;
  52201. };
  52202. Animatable.prototype.stop = function (animationName) {
  52203. if (animationName) {
  52204. var idx = this._scene._activeAnimatables.indexOf(this);
  52205. if (idx > -1) {
  52206. var runtimeAnimations = this._runtimeAnimations;
  52207. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52208. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52209. continue;
  52210. }
  52211. runtimeAnimations[index].dispose();
  52212. runtimeAnimations.splice(index, 1);
  52213. }
  52214. if (runtimeAnimations.length == 0) {
  52215. this._scene._activeAnimatables.splice(idx, 1);
  52216. if (this.onAnimationEnd) {
  52217. this.onAnimationEnd();
  52218. }
  52219. }
  52220. }
  52221. }
  52222. else {
  52223. var index = this._scene._activeAnimatables.indexOf(this);
  52224. if (index > -1) {
  52225. this._scene._activeAnimatables.splice(index, 1);
  52226. var runtimeAnimations = this._runtimeAnimations;
  52227. for (var index = 0; index < runtimeAnimations.length; index++) {
  52228. runtimeAnimations[index].dispose();
  52229. }
  52230. if (this.onAnimationEnd) {
  52231. this.onAnimationEnd();
  52232. }
  52233. }
  52234. }
  52235. };
  52236. Animatable.prototype._animate = function (delay) {
  52237. if (this._paused) {
  52238. this.animationStarted = false;
  52239. if (this._pausedDelay === null) {
  52240. this._pausedDelay = delay;
  52241. }
  52242. return true;
  52243. }
  52244. if (this._localDelayOffset === null) {
  52245. this._localDelayOffset = delay;
  52246. this._pausedDelay = null;
  52247. }
  52248. else if (this._pausedDelay !== null) {
  52249. this._localDelayOffset += delay - this._pausedDelay;
  52250. this._pausedDelay = null;
  52251. }
  52252. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52253. return true;
  52254. }
  52255. // Animating
  52256. var running = false;
  52257. var runtimeAnimations = this._runtimeAnimations;
  52258. var index;
  52259. for (index = 0; index < runtimeAnimations.length; index++) {
  52260. var animation = runtimeAnimations[index];
  52261. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52262. running = running || isRunning;
  52263. }
  52264. this.animationStarted = running;
  52265. if (!running) {
  52266. // Remove from active animatables
  52267. index = this._scene._activeAnimatables.indexOf(this);
  52268. this._scene._activeAnimatables.splice(index, 1);
  52269. // Dispose all runtime animations
  52270. for (index = 0; index < runtimeAnimations.length; index++) {
  52271. runtimeAnimations[index].dispose();
  52272. }
  52273. }
  52274. if (!running && this.onAnimationEnd) {
  52275. this.onAnimationEnd();
  52276. this.onAnimationEnd = null;
  52277. }
  52278. return running;
  52279. };
  52280. return Animatable;
  52281. }());
  52282. BABYLON.Animatable = Animatable;
  52283. })(BABYLON || (BABYLON = {}));
  52284. //# sourceMappingURL=babylon.animatable.js.map
  52285. var BABYLON;
  52286. (function (BABYLON) {
  52287. var EasingFunction = /** @class */ (function () {
  52288. function EasingFunction() {
  52289. // Properties
  52290. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52291. }
  52292. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52293. get: function () {
  52294. return EasingFunction._EASINGMODE_EASEIN;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52300. get: function () {
  52301. return EasingFunction._EASINGMODE_EASEOUT;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52307. get: function () {
  52308. return EasingFunction._EASINGMODE_EASEINOUT;
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52314. var n = Math.min(Math.max(easingMode, 0), 2);
  52315. this._easingMode = n;
  52316. };
  52317. EasingFunction.prototype.getEasingMode = function () {
  52318. return this._easingMode;
  52319. };
  52320. EasingFunction.prototype.easeInCore = function (gradient) {
  52321. throw new Error('You must implement this method');
  52322. };
  52323. EasingFunction.prototype.ease = function (gradient) {
  52324. switch (this._easingMode) {
  52325. case EasingFunction.EASINGMODE_EASEIN:
  52326. return this.easeInCore(gradient);
  52327. case EasingFunction.EASINGMODE_EASEOUT:
  52328. return (1 - this.easeInCore(1 - gradient));
  52329. }
  52330. if (gradient >= 0.5) {
  52331. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52332. }
  52333. return (this.easeInCore(gradient * 2) * 0.5);
  52334. };
  52335. //Statics
  52336. EasingFunction._EASINGMODE_EASEIN = 0;
  52337. EasingFunction._EASINGMODE_EASEOUT = 1;
  52338. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52339. return EasingFunction;
  52340. }());
  52341. BABYLON.EasingFunction = EasingFunction;
  52342. var CircleEase = /** @class */ (function (_super) {
  52343. __extends(CircleEase, _super);
  52344. function CircleEase() {
  52345. return _super !== null && _super.apply(this, arguments) || this;
  52346. }
  52347. CircleEase.prototype.easeInCore = function (gradient) {
  52348. gradient = Math.max(0, Math.min(1, gradient));
  52349. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52350. };
  52351. return CircleEase;
  52352. }(EasingFunction));
  52353. BABYLON.CircleEase = CircleEase;
  52354. var BackEase = /** @class */ (function (_super) {
  52355. __extends(BackEase, _super);
  52356. function BackEase(amplitude) {
  52357. if (amplitude === void 0) { amplitude = 1; }
  52358. var _this = _super.call(this) || this;
  52359. _this.amplitude = amplitude;
  52360. return _this;
  52361. }
  52362. BackEase.prototype.easeInCore = function (gradient) {
  52363. var num = Math.max(0, this.amplitude);
  52364. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52365. };
  52366. return BackEase;
  52367. }(EasingFunction));
  52368. BABYLON.BackEase = BackEase;
  52369. var BounceEase = /** @class */ (function (_super) {
  52370. __extends(BounceEase, _super);
  52371. function BounceEase(bounces, bounciness) {
  52372. if (bounces === void 0) { bounces = 3; }
  52373. if (bounciness === void 0) { bounciness = 2; }
  52374. var _this = _super.call(this) || this;
  52375. _this.bounces = bounces;
  52376. _this.bounciness = bounciness;
  52377. return _this;
  52378. }
  52379. BounceEase.prototype.easeInCore = function (gradient) {
  52380. var y = Math.max(0.0, this.bounces);
  52381. var bounciness = this.bounciness;
  52382. if (bounciness <= 1.0) {
  52383. bounciness = 1.001;
  52384. }
  52385. var num9 = Math.pow(bounciness, y);
  52386. var num5 = 1.0 - bounciness;
  52387. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52388. var num15 = gradient * num4;
  52389. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52390. var num3 = Math.floor(num65);
  52391. var num13 = num3 + 1.0;
  52392. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52393. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52394. var num7 = (num8 + num12) * 0.5;
  52395. var num6 = gradient - num7;
  52396. var num2 = num7 - num8;
  52397. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52398. };
  52399. return BounceEase;
  52400. }(EasingFunction));
  52401. BABYLON.BounceEase = BounceEase;
  52402. var CubicEase = /** @class */ (function (_super) {
  52403. __extends(CubicEase, _super);
  52404. function CubicEase() {
  52405. return _super !== null && _super.apply(this, arguments) || this;
  52406. }
  52407. CubicEase.prototype.easeInCore = function (gradient) {
  52408. return (gradient * gradient * gradient);
  52409. };
  52410. return CubicEase;
  52411. }(EasingFunction));
  52412. BABYLON.CubicEase = CubicEase;
  52413. var ElasticEase = /** @class */ (function (_super) {
  52414. __extends(ElasticEase, _super);
  52415. function ElasticEase(oscillations, springiness) {
  52416. if (oscillations === void 0) { oscillations = 3; }
  52417. if (springiness === void 0) { springiness = 3; }
  52418. var _this = _super.call(this) || this;
  52419. _this.oscillations = oscillations;
  52420. _this.springiness = springiness;
  52421. return _this;
  52422. }
  52423. ElasticEase.prototype.easeInCore = function (gradient) {
  52424. var num2;
  52425. var num3 = Math.max(0.0, this.oscillations);
  52426. var num = Math.max(0.0, this.springiness);
  52427. if (num == 0) {
  52428. num2 = gradient;
  52429. }
  52430. else {
  52431. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52432. }
  52433. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52434. };
  52435. return ElasticEase;
  52436. }(EasingFunction));
  52437. BABYLON.ElasticEase = ElasticEase;
  52438. var ExponentialEase = /** @class */ (function (_super) {
  52439. __extends(ExponentialEase, _super);
  52440. function ExponentialEase(exponent) {
  52441. if (exponent === void 0) { exponent = 2; }
  52442. var _this = _super.call(this) || this;
  52443. _this.exponent = exponent;
  52444. return _this;
  52445. }
  52446. ExponentialEase.prototype.easeInCore = function (gradient) {
  52447. if (this.exponent <= 0) {
  52448. return gradient;
  52449. }
  52450. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52451. };
  52452. return ExponentialEase;
  52453. }(EasingFunction));
  52454. BABYLON.ExponentialEase = ExponentialEase;
  52455. var PowerEase = /** @class */ (function (_super) {
  52456. __extends(PowerEase, _super);
  52457. function PowerEase(power) {
  52458. if (power === void 0) { power = 2; }
  52459. var _this = _super.call(this) || this;
  52460. _this.power = power;
  52461. return _this;
  52462. }
  52463. PowerEase.prototype.easeInCore = function (gradient) {
  52464. var y = Math.max(0.0, this.power);
  52465. return Math.pow(gradient, y);
  52466. };
  52467. return PowerEase;
  52468. }(EasingFunction));
  52469. BABYLON.PowerEase = PowerEase;
  52470. var QuadraticEase = /** @class */ (function (_super) {
  52471. __extends(QuadraticEase, _super);
  52472. function QuadraticEase() {
  52473. return _super !== null && _super.apply(this, arguments) || this;
  52474. }
  52475. QuadraticEase.prototype.easeInCore = function (gradient) {
  52476. return (gradient * gradient);
  52477. };
  52478. return QuadraticEase;
  52479. }(EasingFunction));
  52480. BABYLON.QuadraticEase = QuadraticEase;
  52481. var QuarticEase = /** @class */ (function (_super) {
  52482. __extends(QuarticEase, _super);
  52483. function QuarticEase() {
  52484. return _super !== null && _super.apply(this, arguments) || this;
  52485. }
  52486. QuarticEase.prototype.easeInCore = function (gradient) {
  52487. return (gradient * gradient * gradient * gradient);
  52488. };
  52489. return QuarticEase;
  52490. }(EasingFunction));
  52491. BABYLON.QuarticEase = QuarticEase;
  52492. var QuinticEase = /** @class */ (function (_super) {
  52493. __extends(QuinticEase, _super);
  52494. function QuinticEase() {
  52495. return _super !== null && _super.apply(this, arguments) || this;
  52496. }
  52497. QuinticEase.prototype.easeInCore = function (gradient) {
  52498. return (gradient * gradient * gradient * gradient * gradient);
  52499. };
  52500. return QuinticEase;
  52501. }(EasingFunction));
  52502. BABYLON.QuinticEase = QuinticEase;
  52503. var SineEase = /** @class */ (function (_super) {
  52504. __extends(SineEase, _super);
  52505. function SineEase() {
  52506. return _super !== null && _super.apply(this, arguments) || this;
  52507. }
  52508. SineEase.prototype.easeInCore = function (gradient) {
  52509. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52510. };
  52511. return SineEase;
  52512. }(EasingFunction));
  52513. BABYLON.SineEase = SineEase;
  52514. var BezierCurveEase = /** @class */ (function (_super) {
  52515. __extends(BezierCurveEase, _super);
  52516. function BezierCurveEase(x1, y1, x2, y2) {
  52517. if (x1 === void 0) { x1 = 0; }
  52518. if (y1 === void 0) { y1 = 0; }
  52519. if (x2 === void 0) { x2 = 1; }
  52520. if (y2 === void 0) { y2 = 1; }
  52521. var _this = _super.call(this) || this;
  52522. _this.x1 = x1;
  52523. _this.y1 = y1;
  52524. _this.x2 = x2;
  52525. _this.y2 = y2;
  52526. return _this;
  52527. }
  52528. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52529. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52530. };
  52531. return BezierCurveEase;
  52532. }(EasingFunction));
  52533. BABYLON.BezierCurveEase = BezierCurveEase;
  52534. })(BABYLON || (BABYLON = {}));
  52535. //# sourceMappingURL=babylon.easing.js.map
  52536. var BABYLON;
  52537. (function (BABYLON) {
  52538. /**
  52539. * A Condition applied to an Action
  52540. */
  52541. var Condition = /** @class */ (function () {
  52542. /**
  52543. * Creates a new Condition
  52544. * @param actionManager the manager of the action the condition is applied to
  52545. */
  52546. function Condition(actionManager) {
  52547. this._actionManager = actionManager;
  52548. }
  52549. /**
  52550. * Check if the current condition is valid
  52551. * @returns a boolean
  52552. */
  52553. Condition.prototype.isValid = function () {
  52554. return true;
  52555. };
  52556. /**
  52557. * Internal only
  52558. * @hidden
  52559. */
  52560. Condition.prototype._getProperty = function (propertyPath) {
  52561. return this._actionManager._getProperty(propertyPath);
  52562. };
  52563. /**
  52564. * Internal only
  52565. * @hidden
  52566. */
  52567. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52568. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52569. };
  52570. /**
  52571. * Serialize placeholder for child classes
  52572. * @returns the serialized object
  52573. */
  52574. Condition.prototype.serialize = function () {
  52575. };
  52576. /**
  52577. * Internal only
  52578. * @hidden
  52579. */
  52580. Condition.prototype._serialize = function (serializedCondition) {
  52581. return {
  52582. type: 2,
  52583. children: [],
  52584. name: serializedCondition.name,
  52585. properties: serializedCondition.properties
  52586. };
  52587. };
  52588. return Condition;
  52589. }());
  52590. BABYLON.Condition = Condition;
  52591. /**
  52592. * Defines specific conditional operators as extensions of Condition
  52593. */
  52594. var ValueCondition = /** @class */ (function (_super) {
  52595. __extends(ValueCondition, _super);
  52596. /**
  52597. * Creates a new ValueCondition
  52598. * @param actionManager manager for the action the condition applies to
  52599. * @param target for the action
  52600. * @param propertyPath path to specify the property of the target the conditional operator uses
  52601. * @param value the value compared by the conditional operator against the current value of the property
  52602. * @param operator the conditional operator, default ValueCondition.IsEqual
  52603. */
  52604. function ValueCondition(actionManager, target,
  52605. /** path to specify the property of the target the conditional operator uses */
  52606. propertyPath,
  52607. /** the value compared by the conditional operator against the current value of the property */
  52608. value,
  52609. /** the conditional operator, default ValueCondition.IsEqual */
  52610. operator) {
  52611. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52612. var _this = _super.call(this, actionManager) || this;
  52613. _this.propertyPath = propertyPath;
  52614. _this.value = value;
  52615. _this.operator = operator;
  52616. _this._target = target;
  52617. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52618. _this._property = _this._getProperty(_this.propertyPath);
  52619. return _this;
  52620. }
  52621. Object.defineProperty(ValueCondition, "IsEqual", {
  52622. /**
  52623. * returns the number for IsEqual
  52624. */
  52625. get: function () {
  52626. return ValueCondition._IsEqual;
  52627. },
  52628. enumerable: true,
  52629. configurable: true
  52630. });
  52631. Object.defineProperty(ValueCondition, "IsDifferent", {
  52632. /**
  52633. * Returns the number for IsDifferent
  52634. */
  52635. get: function () {
  52636. return ValueCondition._IsDifferent;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. Object.defineProperty(ValueCondition, "IsGreater", {
  52642. /**
  52643. * Returns the number for IsGreater
  52644. */
  52645. get: function () {
  52646. return ValueCondition._IsGreater;
  52647. },
  52648. enumerable: true,
  52649. configurable: true
  52650. });
  52651. Object.defineProperty(ValueCondition, "IsLesser", {
  52652. /**
  52653. * Returns the number for IsLesser
  52654. */
  52655. get: function () {
  52656. return ValueCondition._IsLesser;
  52657. },
  52658. enumerable: true,
  52659. configurable: true
  52660. });
  52661. /**
  52662. * Compares the given value with the property value for the specified conditional operator
  52663. * @returns the result of the comparison
  52664. */
  52665. ValueCondition.prototype.isValid = function () {
  52666. switch (this.operator) {
  52667. case ValueCondition.IsGreater:
  52668. return this._effectiveTarget[this._property] > this.value;
  52669. case ValueCondition.IsLesser:
  52670. return this._effectiveTarget[this._property] < this.value;
  52671. case ValueCondition.IsEqual:
  52672. case ValueCondition.IsDifferent:
  52673. var check;
  52674. if (this.value.equals) {
  52675. check = this.value.equals(this._effectiveTarget[this._property]);
  52676. }
  52677. else {
  52678. check = this.value === this._effectiveTarget[this._property];
  52679. }
  52680. return this.operator === ValueCondition.IsEqual ? check : !check;
  52681. }
  52682. return false;
  52683. };
  52684. /**
  52685. * Serialize the ValueCondition into a JSON compatible object
  52686. * @returns serialization object
  52687. */
  52688. ValueCondition.prototype.serialize = function () {
  52689. return this._serialize({
  52690. name: "ValueCondition",
  52691. properties: [
  52692. BABYLON.Action._GetTargetProperty(this._target),
  52693. { name: "propertyPath", value: this.propertyPath },
  52694. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52695. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52696. ]
  52697. });
  52698. };
  52699. /**
  52700. * Gets the name of the conditional operator for the ValueCondition
  52701. * @param operator the conditional operator
  52702. * @returns the name
  52703. */
  52704. ValueCondition.GetOperatorName = function (operator) {
  52705. switch (operator) {
  52706. case ValueCondition._IsEqual: return "IsEqual";
  52707. case ValueCondition._IsDifferent: return "IsDifferent";
  52708. case ValueCondition._IsGreater: return "IsGreater";
  52709. case ValueCondition._IsLesser: return "IsLesser";
  52710. default: return "";
  52711. }
  52712. };
  52713. /**
  52714. * Internal only
  52715. * @hidden
  52716. */
  52717. ValueCondition._IsEqual = 0;
  52718. /**
  52719. * Internal only
  52720. * @hidden
  52721. */
  52722. ValueCondition._IsDifferent = 1;
  52723. /**
  52724. * Internal only
  52725. * @hidden
  52726. */
  52727. ValueCondition._IsGreater = 2;
  52728. /**
  52729. * Internal only
  52730. * @hidden
  52731. */
  52732. ValueCondition._IsLesser = 3;
  52733. return ValueCondition;
  52734. }(Condition));
  52735. BABYLON.ValueCondition = ValueCondition;
  52736. /**
  52737. * Defines a predicate condition as an extension of Condition
  52738. */
  52739. var PredicateCondition = /** @class */ (function (_super) {
  52740. __extends(PredicateCondition, _super);
  52741. /**
  52742. * Creates a new PredicateCondition
  52743. * @param actionManager manager for the action the condition applies to
  52744. * @param predicate defines the predicate function used to validate the condition
  52745. */
  52746. function PredicateCondition(actionManager,
  52747. /** defines the predicate function used to validate the condition */
  52748. predicate) {
  52749. var _this = _super.call(this, actionManager) || this;
  52750. _this.predicate = predicate;
  52751. return _this;
  52752. }
  52753. /**
  52754. * @returns the validity of the predicate condition
  52755. */
  52756. PredicateCondition.prototype.isValid = function () {
  52757. return this.predicate();
  52758. };
  52759. return PredicateCondition;
  52760. }(Condition));
  52761. BABYLON.PredicateCondition = PredicateCondition;
  52762. /**
  52763. * Defines a state condition as an extension of Condition
  52764. */
  52765. var StateCondition = /** @class */ (function (_super) {
  52766. __extends(StateCondition, _super);
  52767. /**
  52768. * Creates a new StateCondition
  52769. * @param actionManager manager for the action the condition applies to
  52770. * @param target of the condition
  52771. * @param value to compare with target state
  52772. */
  52773. function StateCondition(actionManager, target, value) {
  52774. var _this = _super.call(this, actionManager) || this;
  52775. _this.value = value;
  52776. _this._target = target;
  52777. return _this;
  52778. }
  52779. /**
  52780. * @returns the validity of the state
  52781. */
  52782. StateCondition.prototype.isValid = function () {
  52783. return this._target.state === this.value;
  52784. };
  52785. /**
  52786. * Serialize the StateCondition into a JSON compatible object
  52787. * @returns serialization object
  52788. */
  52789. StateCondition.prototype.serialize = function () {
  52790. return this._serialize({
  52791. name: "StateCondition",
  52792. properties: [
  52793. BABYLON.Action._GetTargetProperty(this._target),
  52794. { name: "value", value: this.value }
  52795. ]
  52796. });
  52797. };
  52798. return StateCondition;
  52799. }(Condition));
  52800. BABYLON.StateCondition = StateCondition;
  52801. })(BABYLON || (BABYLON = {}));
  52802. //# sourceMappingURL=babylon.condition.js.map
  52803. var BABYLON;
  52804. (function (BABYLON) {
  52805. /**
  52806. * The action to be carried out following a trigger
  52807. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52808. */
  52809. var Action = /** @class */ (function () {
  52810. /**
  52811. * Creates a new Action
  52812. * @param triggerOptions the trigger, with or without parameters, for the action
  52813. * @param condition an optional determinant of action
  52814. */
  52815. function Action(
  52816. /** the trigger, with or without parameters, for the action */
  52817. triggerOptions, condition) {
  52818. this.triggerOptions = triggerOptions;
  52819. /**
  52820. * An event triggered prior to action being executed.
  52821. */
  52822. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52823. if (triggerOptions.parameter) {
  52824. this.trigger = triggerOptions.trigger;
  52825. this._triggerParameter = triggerOptions.parameter;
  52826. }
  52827. else {
  52828. this.trigger = triggerOptions;
  52829. }
  52830. this._nextActiveAction = this;
  52831. this._condition = condition;
  52832. }
  52833. /**
  52834. * Internal only
  52835. * @hidden
  52836. */
  52837. Action.prototype._prepare = function () {
  52838. };
  52839. /**
  52840. * Gets the trigger parameters
  52841. * @returns the trigger parameters
  52842. */
  52843. Action.prototype.getTriggerParameter = function () {
  52844. return this._triggerParameter;
  52845. };
  52846. /**
  52847. * Internal only - executes current action event
  52848. * @hidden
  52849. */
  52850. Action.prototype._executeCurrent = function (evt) {
  52851. if (this._nextActiveAction._condition) {
  52852. var condition = this._nextActiveAction._condition;
  52853. var currentRenderId = this._actionManager.getScene().getRenderId();
  52854. // We cache the current evaluation for the current frame
  52855. if (condition._evaluationId === currentRenderId) {
  52856. if (!condition._currentResult) {
  52857. return;
  52858. }
  52859. }
  52860. else {
  52861. condition._evaluationId = currentRenderId;
  52862. if (!condition.isValid()) {
  52863. condition._currentResult = false;
  52864. return;
  52865. }
  52866. condition._currentResult = true;
  52867. }
  52868. }
  52869. this.onBeforeExecuteObservable.notifyObservers(this);
  52870. this._nextActiveAction.execute(evt);
  52871. this.skipToNextActiveAction();
  52872. };
  52873. /**
  52874. * Execute placeholder for child classes
  52875. * @param evt optional action event
  52876. */
  52877. Action.prototype.execute = function (evt) {
  52878. };
  52879. /**
  52880. * Skips to next active action
  52881. */
  52882. Action.prototype.skipToNextActiveAction = function () {
  52883. if (this._nextActiveAction._child) {
  52884. if (!this._nextActiveAction._child._actionManager) {
  52885. this._nextActiveAction._child._actionManager = this._actionManager;
  52886. }
  52887. this._nextActiveAction = this._nextActiveAction._child;
  52888. }
  52889. else {
  52890. this._nextActiveAction = this;
  52891. }
  52892. };
  52893. /**
  52894. * Adds action to chain of actions, may be a DoNothingAction
  52895. * @param action defines the next action to execute
  52896. * @returns The action passed in
  52897. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52898. */
  52899. Action.prototype.then = function (action) {
  52900. this._child = action;
  52901. action._actionManager = this._actionManager;
  52902. action._prepare();
  52903. return action;
  52904. };
  52905. /**
  52906. * Internal only
  52907. * @hidden
  52908. */
  52909. Action.prototype._getProperty = function (propertyPath) {
  52910. return this._actionManager._getProperty(propertyPath);
  52911. };
  52912. /**
  52913. * Internal only
  52914. * @hidden
  52915. */
  52916. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52917. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52918. };
  52919. /**
  52920. * Serialize placeholder for child classes
  52921. * @param parent of child
  52922. * @returns the serialized object
  52923. */
  52924. Action.prototype.serialize = function (parent) {
  52925. };
  52926. /**
  52927. * Internal only called by serialize
  52928. * @hidden
  52929. */
  52930. Action.prototype._serialize = function (serializedAction, parent) {
  52931. var serializationObject = {
  52932. type: 1,
  52933. children: [],
  52934. name: serializedAction.name,
  52935. properties: serializedAction.properties || []
  52936. };
  52937. // Serialize child
  52938. if (this._child) {
  52939. this._child.serialize(serializationObject);
  52940. }
  52941. // Check if "this" has a condition
  52942. if (this._condition) {
  52943. var serializedCondition = this._condition.serialize();
  52944. serializedCondition.children.push(serializationObject);
  52945. if (parent) {
  52946. parent.children.push(serializedCondition);
  52947. }
  52948. return serializedCondition;
  52949. }
  52950. if (parent) {
  52951. parent.children.push(serializationObject);
  52952. }
  52953. return serializationObject;
  52954. };
  52955. /**
  52956. * Internal only
  52957. * @hidden
  52958. */
  52959. Action._SerializeValueAsString = function (value) {
  52960. if (typeof value === "number") {
  52961. return value.toString();
  52962. }
  52963. if (typeof value === "boolean") {
  52964. return value ? "true" : "false";
  52965. }
  52966. if (value instanceof BABYLON.Vector2) {
  52967. return value.x + ", " + value.y;
  52968. }
  52969. if (value instanceof BABYLON.Vector3) {
  52970. return value.x + ", " + value.y + ", " + value.z;
  52971. }
  52972. if (value instanceof BABYLON.Color3) {
  52973. return value.r + ", " + value.g + ", " + value.b;
  52974. }
  52975. if (value instanceof BABYLON.Color4) {
  52976. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52977. }
  52978. return value; // string
  52979. };
  52980. /**
  52981. * Internal only
  52982. * @hidden
  52983. */
  52984. Action._GetTargetProperty = function (target) {
  52985. return {
  52986. name: "target",
  52987. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52988. : target instanceof BABYLON.Light ? "LightProperties"
  52989. : target instanceof BABYLON.Camera ? "CameraProperties"
  52990. : "SceneProperties",
  52991. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52992. };
  52993. };
  52994. return Action;
  52995. }());
  52996. BABYLON.Action = Action;
  52997. })(BABYLON || (BABYLON = {}));
  52998. //# sourceMappingURL=babylon.action.js.map
  52999. var BABYLON;
  53000. (function (BABYLON) {
  53001. /**
  53002. * ActionEvent is the event being sent when an action is triggered.
  53003. */
  53004. var ActionEvent = /** @class */ (function () {
  53005. /**
  53006. * Creates a new ActionEvent
  53007. * @param source The mesh or sprite that triggered the action
  53008. * @param pointerX The X mouse cursor position at the time of the event
  53009. * @param pointerY The Y mouse cursor position at the time of the event
  53010. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53011. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53012. * @param additionalData additional data for the event
  53013. */
  53014. function ActionEvent(
  53015. /** The mesh or sprite that triggered the action */
  53016. source,
  53017. /** The X mouse cursor position at the time of the event */
  53018. pointerX,
  53019. /** The Y mouse cursor position at the time of the event */
  53020. pointerY,
  53021. /** The mesh that is currently pointed at (can be null) */
  53022. meshUnderPointer,
  53023. /** the original (browser) event that triggered the ActionEvent */
  53024. sourceEvent,
  53025. /** additional data for the event */
  53026. additionalData) {
  53027. this.source = source;
  53028. this.pointerX = pointerX;
  53029. this.pointerY = pointerY;
  53030. this.meshUnderPointer = meshUnderPointer;
  53031. this.sourceEvent = sourceEvent;
  53032. this.additionalData = additionalData;
  53033. }
  53034. /**
  53035. * Helper function to auto-create an ActionEvent from a source mesh.
  53036. * @param source The source mesh that triggered the event
  53037. * @param evt The original (browser) event
  53038. * @param additionalData additional data for the event
  53039. * @returns the new ActionEvent
  53040. */
  53041. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53042. var scene = source.getScene();
  53043. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53044. };
  53045. /**
  53046. * Helper function to auto-create an ActionEvent from a source sprite
  53047. * @param source The source sprite that triggered the event
  53048. * @param scene Scene associated with the sprite
  53049. * @param evt The original (browser) event
  53050. * @param additionalData additional data for the event
  53051. * @returns the new ActionEvent
  53052. */
  53053. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53054. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53055. };
  53056. /**
  53057. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53058. * @param scene the scene where the event occurred
  53059. * @param evt The original (browser) event
  53060. * @returns the new ActionEvent
  53061. */
  53062. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53063. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53064. };
  53065. /**
  53066. * Helper function to auto-create an ActionEvent from a primitive
  53067. * @param prim defines the target primitive
  53068. * @param pointerPos defines the pointer position
  53069. * @param evt The original (browser) event
  53070. * @param additionalData additional data for the event
  53071. * @returns the new ActionEvent
  53072. */
  53073. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53074. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53075. };
  53076. return ActionEvent;
  53077. }());
  53078. BABYLON.ActionEvent = ActionEvent;
  53079. /**
  53080. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53081. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53082. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53083. */
  53084. var ActionManager = /** @class */ (function () {
  53085. /**
  53086. * Creates a new action manager
  53087. * @param scene defines the hosting scene
  53088. */
  53089. function ActionManager(scene) {
  53090. // Members
  53091. /** Gets the list of actions */
  53092. this.actions = new Array();
  53093. /** Gets the cursor to use when hovering items */
  53094. this.hoverCursor = '';
  53095. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53096. scene._actionManagers.push(this);
  53097. }
  53098. Object.defineProperty(ActionManager, "NothingTrigger", {
  53099. /**
  53100. * Nothing
  53101. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53102. */
  53103. get: function () {
  53104. return ActionManager._NothingTrigger;
  53105. },
  53106. enumerable: true,
  53107. configurable: true
  53108. });
  53109. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53110. /**
  53111. * On pick
  53112. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53113. */
  53114. get: function () {
  53115. return ActionManager._OnPickTrigger;
  53116. },
  53117. enumerable: true,
  53118. configurable: true
  53119. });
  53120. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53121. /**
  53122. * On left pick
  53123. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53124. */
  53125. get: function () {
  53126. return ActionManager._OnLeftPickTrigger;
  53127. },
  53128. enumerable: true,
  53129. configurable: true
  53130. });
  53131. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53132. /**
  53133. * On right pick
  53134. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53135. */
  53136. get: function () {
  53137. return ActionManager._OnRightPickTrigger;
  53138. },
  53139. enumerable: true,
  53140. configurable: true
  53141. });
  53142. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53143. /**
  53144. * On center pick
  53145. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53146. */
  53147. get: function () {
  53148. return ActionManager._OnCenterPickTrigger;
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53154. /**
  53155. * On pick down
  53156. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53157. */
  53158. get: function () {
  53159. return ActionManager._OnPickDownTrigger;
  53160. },
  53161. enumerable: true,
  53162. configurable: true
  53163. });
  53164. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53165. /**
  53166. * On double pick
  53167. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53168. */
  53169. get: function () {
  53170. return ActionManager._OnDoublePickTrigger;
  53171. },
  53172. enumerable: true,
  53173. configurable: true
  53174. });
  53175. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53176. /**
  53177. * On pick up
  53178. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53179. */
  53180. get: function () {
  53181. return ActionManager._OnPickUpTrigger;
  53182. },
  53183. enumerable: true,
  53184. configurable: true
  53185. });
  53186. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53187. /**
  53188. * On pick out.
  53189. * This trigger will only be raised if you also declared a OnPickDown
  53190. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53191. */
  53192. get: function () {
  53193. return ActionManager._OnPickOutTrigger;
  53194. },
  53195. enumerable: true,
  53196. configurable: true
  53197. });
  53198. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53199. /**
  53200. * On long press
  53201. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53202. */
  53203. get: function () {
  53204. return ActionManager._OnLongPressTrigger;
  53205. },
  53206. enumerable: true,
  53207. configurable: true
  53208. });
  53209. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53210. /**
  53211. * On pointer over
  53212. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53213. */
  53214. get: function () {
  53215. return ActionManager._OnPointerOverTrigger;
  53216. },
  53217. enumerable: true,
  53218. configurable: true
  53219. });
  53220. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53221. /**
  53222. * On pointer out
  53223. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53224. */
  53225. get: function () {
  53226. return ActionManager._OnPointerOutTrigger;
  53227. },
  53228. enumerable: true,
  53229. configurable: true
  53230. });
  53231. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53232. /**
  53233. * On every frame
  53234. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53235. */
  53236. get: function () {
  53237. return ActionManager._OnEveryFrameTrigger;
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53243. /**
  53244. * On intersection enter
  53245. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53246. */
  53247. get: function () {
  53248. return ActionManager._OnIntersectionEnterTrigger;
  53249. },
  53250. enumerable: true,
  53251. configurable: true
  53252. });
  53253. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53254. /**
  53255. * On intersection exit
  53256. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53257. */
  53258. get: function () {
  53259. return ActionManager._OnIntersectionExitTrigger;
  53260. },
  53261. enumerable: true,
  53262. configurable: true
  53263. });
  53264. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53265. /**
  53266. * On key down
  53267. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53268. */
  53269. get: function () {
  53270. return ActionManager._OnKeyDownTrigger;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53276. /**
  53277. * On key up
  53278. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53279. */
  53280. get: function () {
  53281. return ActionManager._OnKeyUpTrigger;
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. // Methods
  53287. /**
  53288. * Releases all associated resources
  53289. */
  53290. ActionManager.prototype.dispose = function () {
  53291. var index = this._scene._actionManagers.indexOf(this);
  53292. for (var i = 0; i < this.actions.length; i++) {
  53293. var action = this.actions[i];
  53294. ActionManager.Triggers[action.trigger]--;
  53295. if (ActionManager.Triggers[action.trigger] === 0) {
  53296. delete ActionManager.Triggers[action.trigger];
  53297. }
  53298. }
  53299. if (index > -1) {
  53300. this._scene._actionManagers.splice(index, 1);
  53301. }
  53302. };
  53303. /**
  53304. * Gets hosting scene
  53305. * @returns the hosting scene
  53306. */
  53307. ActionManager.prototype.getScene = function () {
  53308. return this._scene;
  53309. };
  53310. /**
  53311. * Does this action manager handles actions of any of the given triggers
  53312. * @param triggers defines the triggers to be tested
  53313. * @return a boolean indicating whether one (or more) of the triggers is handled
  53314. */
  53315. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53316. for (var index = 0; index < this.actions.length; index++) {
  53317. var action = this.actions[index];
  53318. if (triggers.indexOf(action.trigger) > -1) {
  53319. return true;
  53320. }
  53321. }
  53322. return false;
  53323. };
  53324. /**
  53325. * Does this action manager handles actions of a given trigger
  53326. * @param trigger defines the trigger to be tested
  53327. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53328. * @return whether the trigger is handled
  53329. */
  53330. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53331. for (var index = 0; index < this.actions.length; index++) {
  53332. var action = this.actions[index];
  53333. if (action.trigger === trigger) {
  53334. if (parameterPredicate) {
  53335. if (parameterPredicate(action.getTriggerParameter())) {
  53336. return true;
  53337. }
  53338. }
  53339. else {
  53340. return true;
  53341. }
  53342. }
  53343. }
  53344. return false;
  53345. };
  53346. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53347. /**
  53348. * Does this action manager has pointer triggers
  53349. */
  53350. get: function () {
  53351. for (var index = 0; index < this.actions.length; index++) {
  53352. var action = this.actions[index];
  53353. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53354. return true;
  53355. }
  53356. }
  53357. return false;
  53358. },
  53359. enumerable: true,
  53360. configurable: true
  53361. });
  53362. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53363. /**
  53364. * Does this action manager has pick triggers
  53365. */
  53366. get: function () {
  53367. for (var index = 0; index < this.actions.length; index++) {
  53368. var action = this.actions[index];
  53369. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53370. return true;
  53371. }
  53372. }
  53373. return false;
  53374. },
  53375. enumerable: true,
  53376. configurable: true
  53377. });
  53378. Object.defineProperty(ActionManager, "HasTriggers", {
  53379. /**
  53380. * Does exist one action manager with at least one trigger
  53381. **/
  53382. get: function () {
  53383. for (var t in ActionManager.Triggers) {
  53384. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53385. return true;
  53386. }
  53387. }
  53388. return false;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53394. /**
  53395. * Does exist one action manager with at least one pick trigger
  53396. **/
  53397. get: function () {
  53398. for (var t in ActionManager.Triggers) {
  53399. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53400. var t_int = parseInt(t);
  53401. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53402. return true;
  53403. }
  53404. }
  53405. }
  53406. return false;
  53407. },
  53408. enumerable: true,
  53409. configurable: true
  53410. });
  53411. /**
  53412. * Does exist one action manager that handles actions of a given trigger
  53413. * @param trigger defines the trigger to be tested
  53414. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53415. **/
  53416. ActionManager.HasSpecificTrigger = function (trigger) {
  53417. for (var t in ActionManager.Triggers) {
  53418. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53419. var t_int = parseInt(t);
  53420. if (t_int === trigger) {
  53421. return true;
  53422. }
  53423. }
  53424. }
  53425. return false;
  53426. };
  53427. /**
  53428. * Registers an action to this action manager
  53429. * @param action defines the action to be registered
  53430. * @return the action amended (prepared) after registration
  53431. */
  53432. ActionManager.prototype.registerAction = function (action) {
  53433. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53434. if (this.getScene().actionManager !== this) {
  53435. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53436. return null;
  53437. }
  53438. }
  53439. this.actions.push(action);
  53440. if (ActionManager.Triggers[action.trigger]) {
  53441. ActionManager.Triggers[action.trigger]++;
  53442. }
  53443. else {
  53444. ActionManager.Triggers[action.trigger] = 1;
  53445. }
  53446. action._actionManager = this;
  53447. action._prepare();
  53448. return action;
  53449. };
  53450. /**
  53451. * Unregisters an action to this action manager
  53452. * @param action defines the action to be unregistered
  53453. * @return a boolean indicating whether the action has been unregistered
  53454. */
  53455. ActionManager.prototype.unregisterAction = function (action) {
  53456. var index = this.actions.indexOf(action);
  53457. if (index !== -1) {
  53458. this.actions.splice(index, 1);
  53459. ActionManager.Triggers[action.trigger] -= 1;
  53460. if (ActionManager.Triggers[action.trigger] === 0) {
  53461. delete ActionManager.Triggers[action.trigger];
  53462. }
  53463. delete action._actionManager;
  53464. return true;
  53465. }
  53466. return false;
  53467. };
  53468. /**
  53469. * Process a specific trigger
  53470. * @param trigger defines the trigger to process
  53471. * @param evt defines the event details to be processed
  53472. */
  53473. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53474. for (var index = 0; index < this.actions.length; index++) {
  53475. var action = this.actions[index];
  53476. if (action.trigger === trigger) {
  53477. if (evt) {
  53478. if (trigger === ActionManager.OnKeyUpTrigger
  53479. || trigger === ActionManager.OnKeyDownTrigger) {
  53480. var parameter = action.getTriggerParameter();
  53481. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53482. if (!parameter.toLowerCase) {
  53483. continue;
  53484. }
  53485. var lowerCase = parameter.toLowerCase();
  53486. if (lowerCase !== evt.sourceEvent.key) {
  53487. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53488. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53489. if (actualkey !== lowerCase) {
  53490. continue;
  53491. }
  53492. }
  53493. }
  53494. }
  53495. }
  53496. action._executeCurrent(evt);
  53497. }
  53498. }
  53499. };
  53500. /** @hidden */
  53501. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53502. var properties = propertyPath.split(".");
  53503. for (var index = 0; index < properties.length - 1; index++) {
  53504. target = target[properties[index]];
  53505. }
  53506. return target;
  53507. };
  53508. /** @hidden */
  53509. ActionManager.prototype._getProperty = function (propertyPath) {
  53510. var properties = propertyPath.split(".");
  53511. return properties[properties.length - 1];
  53512. };
  53513. /**
  53514. * Serialize this manager to a JSON object
  53515. * @param name defines the property name to store this manager
  53516. * @returns a JSON representation of this manager
  53517. */
  53518. ActionManager.prototype.serialize = function (name) {
  53519. var root = {
  53520. children: new Array(),
  53521. name: name,
  53522. type: 3,
  53523. properties: new Array() // Empty for root but required
  53524. };
  53525. for (var i = 0; i < this.actions.length; i++) {
  53526. var triggerObject = {
  53527. type: 0,
  53528. children: new Array(),
  53529. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53530. properties: new Array()
  53531. };
  53532. var triggerOptions = this.actions[i].triggerOptions;
  53533. if (triggerOptions && typeof triggerOptions !== "number") {
  53534. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53535. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53536. }
  53537. else {
  53538. var parameter = {};
  53539. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53540. if (triggerOptions.parameter.mesh) {
  53541. parameter._meshId = triggerOptions.parameter.mesh.id;
  53542. }
  53543. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53544. }
  53545. }
  53546. // Serialize child action, recursively
  53547. this.actions[i].serialize(triggerObject);
  53548. // Add serialized trigger
  53549. root.children.push(triggerObject);
  53550. }
  53551. return root;
  53552. };
  53553. /**
  53554. * Creates a new ActionManager from a JSON data
  53555. * @param parsedActions defines the JSON data to read from
  53556. * @param object defines the hosting mesh
  53557. * @param scene defines the hosting scene
  53558. */
  53559. ActionManager.Parse = function (parsedActions, object, scene) {
  53560. var actionManager = new ActionManager(scene);
  53561. if (object === null)
  53562. scene.actionManager = actionManager;
  53563. else
  53564. object.actionManager = actionManager;
  53565. // instanciate a new object
  53566. var instanciate = function (name, params) {
  53567. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53568. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53569. newInstance.constructor.apply(newInstance, params);
  53570. return newInstance;
  53571. };
  53572. var parseParameter = function (name, value, target, propertyPath) {
  53573. if (propertyPath === null) {
  53574. // String, boolean or float
  53575. var floatValue = parseFloat(value);
  53576. if (value === "true" || value === "false")
  53577. return value === "true";
  53578. else
  53579. return isNaN(floatValue) ? value : floatValue;
  53580. }
  53581. var effectiveTarget = propertyPath.split(".");
  53582. var values = value.split(",");
  53583. // Get effective Target
  53584. for (var i = 0; i < effectiveTarget.length; i++) {
  53585. target = target[effectiveTarget[i]];
  53586. }
  53587. // Return appropriate value with its type
  53588. if (typeof (target) === "boolean")
  53589. return values[0] === "true";
  53590. if (typeof (target) === "string")
  53591. return values[0];
  53592. // Parameters with multiple values such as Vector3 etc.
  53593. var split = new Array();
  53594. for (var i = 0; i < values.length; i++)
  53595. split.push(parseFloat(values[i]));
  53596. if (target instanceof BABYLON.Vector3)
  53597. return BABYLON.Vector3.FromArray(split);
  53598. if (target instanceof BABYLON.Vector4)
  53599. return BABYLON.Vector4.FromArray(split);
  53600. if (target instanceof BABYLON.Color3)
  53601. return BABYLON.Color3.FromArray(split);
  53602. if (target instanceof BABYLON.Color4)
  53603. return BABYLON.Color4.FromArray(split);
  53604. return parseFloat(values[0]);
  53605. };
  53606. // traverse graph per trigger
  53607. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53608. if (combineArray === void 0) { combineArray = null; }
  53609. if (parsedAction.detached)
  53610. return;
  53611. var parameters = new Array();
  53612. var target = null;
  53613. var propertyPath = null;
  53614. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53615. // Parameters
  53616. if (parsedAction.type === 2)
  53617. parameters.push(actionManager);
  53618. else
  53619. parameters.push(trigger);
  53620. if (combine) {
  53621. var actions = new Array();
  53622. for (var j = 0; j < parsedAction.combine.length; j++) {
  53623. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53624. }
  53625. parameters.push(actions);
  53626. }
  53627. else {
  53628. for (var i = 0; i < parsedAction.properties.length; i++) {
  53629. var value = parsedAction.properties[i].value;
  53630. var name = parsedAction.properties[i].name;
  53631. var targetType = parsedAction.properties[i].targetType;
  53632. if (name === "target")
  53633. if (targetType !== null && targetType === "SceneProperties")
  53634. value = target = scene;
  53635. else
  53636. value = target = scene.getNodeByName(value);
  53637. else if (name === "parent")
  53638. value = scene.getNodeByName(value);
  53639. else if (name === "sound")
  53640. value = scene.getSoundByName(value);
  53641. else if (name !== "propertyPath") {
  53642. if (parsedAction.type === 2 && name === "operator")
  53643. value = BABYLON.ValueCondition[value];
  53644. else
  53645. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53646. }
  53647. else {
  53648. propertyPath = value;
  53649. }
  53650. parameters.push(value);
  53651. }
  53652. }
  53653. if (combineArray === null) {
  53654. parameters.push(condition);
  53655. }
  53656. else {
  53657. parameters.push(null);
  53658. }
  53659. // If interpolate value action
  53660. if (parsedAction.name === "InterpolateValueAction") {
  53661. var param = parameters[parameters.length - 2];
  53662. parameters[parameters.length - 1] = param;
  53663. parameters[parameters.length - 2] = condition;
  53664. }
  53665. // Action or condition(s) and not CombineAction
  53666. var newAction = instanciate(parsedAction.name, parameters);
  53667. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53668. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53669. if (action)
  53670. action.then(nothing);
  53671. else
  53672. actionManager.registerAction(nothing);
  53673. action = nothing;
  53674. }
  53675. if (combineArray === null) {
  53676. if (newAction instanceof BABYLON.Condition) {
  53677. condition = newAction;
  53678. newAction = action;
  53679. }
  53680. else {
  53681. condition = null;
  53682. if (action)
  53683. action.then(newAction);
  53684. else
  53685. actionManager.registerAction(newAction);
  53686. }
  53687. }
  53688. else {
  53689. combineArray.push(newAction);
  53690. }
  53691. for (var i = 0; i < parsedAction.children.length; i++)
  53692. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53693. };
  53694. // triggers
  53695. for (var i = 0; i < parsedActions.children.length; i++) {
  53696. var triggerParams;
  53697. var trigger = parsedActions.children[i];
  53698. if (trigger.properties.length > 0) {
  53699. var param = trigger.properties[0].value;
  53700. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53701. if (value._meshId) {
  53702. value.mesh = scene.getMeshByID(value._meshId);
  53703. }
  53704. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53705. }
  53706. else
  53707. triggerParams = ActionManager[trigger.name];
  53708. for (var j = 0; j < trigger.children.length; j++) {
  53709. if (!trigger.detached)
  53710. traverse(trigger.children[j], triggerParams, null, null);
  53711. }
  53712. }
  53713. };
  53714. /**
  53715. * Get a trigger name by index
  53716. * @param trigger defines the trigger index
  53717. * @returns a trigger name
  53718. */
  53719. ActionManager.GetTriggerName = function (trigger) {
  53720. switch (trigger) {
  53721. case 0: return "NothingTrigger";
  53722. case 1: return "OnPickTrigger";
  53723. case 2: return "OnLeftPickTrigger";
  53724. case 3: return "OnRightPickTrigger";
  53725. case 4: return "OnCenterPickTrigger";
  53726. case 5: return "OnPickDownTrigger";
  53727. case 6: return "OnPickUpTrigger";
  53728. case 7: return "OnLongPressTrigger";
  53729. case 8: return "OnPointerOverTrigger";
  53730. case 9: return "OnPointerOutTrigger";
  53731. case 10: return "OnEveryFrameTrigger";
  53732. case 11: return "OnIntersectionEnterTrigger";
  53733. case 12: return "OnIntersectionExitTrigger";
  53734. case 13: return "OnKeyDownTrigger";
  53735. case 14: return "OnKeyUpTrigger";
  53736. case 15: return "OnPickOutTrigger";
  53737. default: return "";
  53738. }
  53739. };
  53740. // Statics
  53741. ActionManager._NothingTrigger = 0;
  53742. ActionManager._OnPickTrigger = 1;
  53743. ActionManager._OnLeftPickTrigger = 2;
  53744. ActionManager._OnRightPickTrigger = 3;
  53745. ActionManager._OnCenterPickTrigger = 4;
  53746. ActionManager._OnPickDownTrigger = 5;
  53747. ActionManager._OnDoublePickTrigger = 6;
  53748. ActionManager._OnPickUpTrigger = 7;
  53749. ActionManager._OnLongPressTrigger = 8;
  53750. ActionManager._OnPointerOverTrigger = 9;
  53751. ActionManager._OnPointerOutTrigger = 10;
  53752. ActionManager._OnEveryFrameTrigger = 11;
  53753. ActionManager._OnIntersectionEnterTrigger = 12;
  53754. ActionManager._OnIntersectionExitTrigger = 13;
  53755. ActionManager._OnKeyDownTrigger = 14;
  53756. ActionManager._OnKeyUpTrigger = 15;
  53757. ActionManager._OnPickOutTrigger = 16;
  53758. /** Gets the list of active triggers */
  53759. ActionManager.Triggers = {};
  53760. return ActionManager;
  53761. }());
  53762. BABYLON.ActionManager = ActionManager;
  53763. })(BABYLON || (BABYLON = {}));
  53764. //# sourceMappingURL=babylon.actionManager.js.map
  53765. var BABYLON;
  53766. (function (BABYLON) {
  53767. var InterpolateValueAction = /** @class */ (function (_super) {
  53768. __extends(InterpolateValueAction, _super);
  53769. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53770. if (duration === void 0) { duration = 1000; }
  53771. var _this = _super.call(this, triggerOptions, condition) || this;
  53772. _this.propertyPath = propertyPath;
  53773. _this.value = value;
  53774. _this.duration = duration;
  53775. _this.stopOtherAnimations = stopOtherAnimations;
  53776. _this.onInterpolationDone = onInterpolationDone;
  53777. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53778. _this._target = _this._effectiveTarget = target;
  53779. return _this;
  53780. }
  53781. InterpolateValueAction.prototype._prepare = function () {
  53782. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53783. this._property = this._getProperty(this.propertyPath);
  53784. };
  53785. InterpolateValueAction.prototype.execute = function () {
  53786. var _this = this;
  53787. var scene = this._actionManager.getScene();
  53788. var keys = [
  53789. {
  53790. frame: 0,
  53791. value: this._effectiveTarget[this._property]
  53792. }, {
  53793. frame: 100,
  53794. value: this.value
  53795. }
  53796. ];
  53797. var dataType;
  53798. if (typeof this.value === "number") {
  53799. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53800. }
  53801. else if (this.value instanceof BABYLON.Color3) {
  53802. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53803. }
  53804. else if (this.value instanceof BABYLON.Vector3) {
  53805. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53806. }
  53807. else if (this.value instanceof BABYLON.Matrix) {
  53808. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53809. }
  53810. else if (this.value instanceof BABYLON.Quaternion) {
  53811. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53812. }
  53813. else {
  53814. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53815. return;
  53816. }
  53817. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53818. animation.setKeys(keys);
  53819. if (this.stopOtherAnimations) {
  53820. scene.stopAnimation(this._effectiveTarget);
  53821. }
  53822. var wrapper = function () {
  53823. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53824. if (_this.onInterpolationDone) {
  53825. _this.onInterpolationDone();
  53826. }
  53827. };
  53828. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53829. };
  53830. InterpolateValueAction.prototype.serialize = function (parent) {
  53831. return _super.prototype._serialize.call(this, {
  53832. name: "InterpolateValueAction",
  53833. properties: [
  53834. BABYLON.Action._GetTargetProperty(this._target),
  53835. { name: "propertyPath", value: this.propertyPath },
  53836. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53837. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53838. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53839. ]
  53840. }, parent);
  53841. };
  53842. return InterpolateValueAction;
  53843. }(BABYLON.Action));
  53844. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53845. })(BABYLON || (BABYLON = {}));
  53846. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53847. var BABYLON;
  53848. (function (BABYLON) {
  53849. var SwitchBooleanAction = /** @class */ (function (_super) {
  53850. __extends(SwitchBooleanAction, _super);
  53851. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53852. var _this = _super.call(this, triggerOptions, condition) || this;
  53853. _this.propertyPath = propertyPath;
  53854. _this._target = _this._effectiveTarget = target;
  53855. return _this;
  53856. }
  53857. SwitchBooleanAction.prototype._prepare = function () {
  53858. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53859. this._property = this._getProperty(this.propertyPath);
  53860. };
  53861. SwitchBooleanAction.prototype.execute = function () {
  53862. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53863. };
  53864. SwitchBooleanAction.prototype.serialize = function (parent) {
  53865. return _super.prototype._serialize.call(this, {
  53866. name: "SwitchBooleanAction",
  53867. properties: [
  53868. BABYLON.Action._GetTargetProperty(this._target),
  53869. { name: "propertyPath", value: this.propertyPath }
  53870. ]
  53871. }, parent);
  53872. };
  53873. return SwitchBooleanAction;
  53874. }(BABYLON.Action));
  53875. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53876. var SetStateAction = /** @class */ (function (_super) {
  53877. __extends(SetStateAction, _super);
  53878. function SetStateAction(triggerOptions, target, value, condition) {
  53879. var _this = _super.call(this, triggerOptions, condition) || this;
  53880. _this.value = value;
  53881. _this._target = target;
  53882. return _this;
  53883. }
  53884. SetStateAction.prototype.execute = function () {
  53885. this._target.state = this.value;
  53886. };
  53887. SetStateAction.prototype.serialize = function (parent) {
  53888. return _super.prototype._serialize.call(this, {
  53889. name: "SetStateAction",
  53890. properties: [
  53891. BABYLON.Action._GetTargetProperty(this._target),
  53892. { name: "value", value: this.value }
  53893. ]
  53894. }, parent);
  53895. };
  53896. return SetStateAction;
  53897. }(BABYLON.Action));
  53898. BABYLON.SetStateAction = SetStateAction;
  53899. var SetValueAction = /** @class */ (function (_super) {
  53900. __extends(SetValueAction, _super);
  53901. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53902. var _this = _super.call(this, triggerOptions, condition) || this;
  53903. _this.propertyPath = propertyPath;
  53904. _this.value = value;
  53905. _this._target = _this._effectiveTarget = target;
  53906. return _this;
  53907. }
  53908. SetValueAction.prototype._prepare = function () {
  53909. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53910. this._property = this._getProperty(this.propertyPath);
  53911. };
  53912. SetValueAction.prototype.execute = function () {
  53913. this._effectiveTarget[this._property] = this.value;
  53914. if (this._target.markAsDirty) {
  53915. this._target.markAsDirty(this._property);
  53916. }
  53917. };
  53918. SetValueAction.prototype.serialize = function (parent) {
  53919. return _super.prototype._serialize.call(this, {
  53920. name: "SetValueAction",
  53921. properties: [
  53922. BABYLON.Action._GetTargetProperty(this._target),
  53923. { name: "propertyPath", value: this.propertyPath },
  53924. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53925. ]
  53926. }, parent);
  53927. };
  53928. return SetValueAction;
  53929. }(BABYLON.Action));
  53930. BABYLON.SetValueAction = SetValueAction;
  53931. var IncrementValueAction = /** @class */ (function (_super) {
  53932. __extends(IncrementValueAction, _super);
  53933. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53934. var _this = _super.call(this, triggerOptions, condition) || this;
  53935. _this.propertyPath = propertyPath;
  53936. _this.value = value;
  53937. _this._target = _this._effectiveTarget = target;
  53938. return _this;
  53939. }
  53940. IncrementValueAction.prototype._prepare = function () {
  53941. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53942. this._property = this._getProperty(this.propertyPath);
  53943. if (typeof this._effectiveTarget[this._property] !== "number") {
  53944. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53945. }
  53946. };
  53947. IncrementValueAction.prototype.execute = function () {
  53948. this._effectiveTarget[this._property] += this.value;
  53949. if (this._target.markAsDirty) {
  53950. this._target.markAsDirty(this._property);
  53951. }
  53952. };
  53953. IncrementValueAction.prototype.serialize = function (parent) {
  53954. return _super.prototype._serialize.call(this, {
  53955. name: "IncrementValueAction",
  53956. properties: [
  53957. BABYLON.Action._GetTargetProperty(this._target),
  53958. { name: "propertyPath", value: this.propertyPath },
  53959. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53960. ]
  53961. }, parent);
  53962. };
  53963. return IncrementValueAction;
  53964. }(BABYLON.Action));
  53965. BABYLON.IncrementValueAction = IncrementValueAction;
  53966. var PlayAnimationAction = /** @class */ (function (_super) {
  53967. __extends(PlayAnimationAction, _super);
  53968. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53969. var _this = _super.call(this, triggerOptions, condition) || this;
  53970. _this.from = from;
  53971. _this.to = to;
  53972. _this.loop = loop;
  53973. _this._target = target;
  53974. return _this;
  53975. }
  53976. PlayAnimationAction.prototype._prepare = function () {
  53977. };
  53978. PlayAnimationAction.prototype.execute = function () {
  53979. var scene = this._actionManager.getScene();
  53980. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53981. };
  53982. PlayAnimationAction.prototype.serialize = function (parent) {
  53983. return _super.prototype._serialize.call(this, {
  53984. name: "PlayAnimationAction",
  53985. properties: [
  53986. BABYLON.Action._GetTargetProperty(this._target),
  53987. { name: "from", value: String(this.from) },
  53988. { name: "to", value: String(this.to) },
  53989. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53990. ]
  53991. }, parent);
  53992. };
  53993. return PlayAnimationAction;
  53994. }(BABYLON.Action));
  53995. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53996. var StopAnimationAction = /** @class */ (function (_super) {
  53997. __extends(StopAnimationAction, _super);
  53998. function StopAnimationAction(triggerOptions, target, condition) {
  53999. var _this = _super.call(this, triggerOptions, condition) || this;
  54000. _this._target = target;
  54001. return _this;
  54002. }
  54003. StopAnimationAction.prototype._prepare = function () {
  54004. };
  54005. StopAnimationAction.prototype.execute = function () {
  54006. var scene = this._actionManager.getScene();
  54007. scene.stopAnimation(this._target);
  54008. };
  54009. StopAnimationAction.prototype.serialize = function (parent) {
  54010. return _super.prototype._serialize.call(this, {
  54011. name: "StopAnimationAction",
  54012. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54013. }, parent);
  54014. };
  54015. return StopAnimationAction;
  54016. }(BABYLON.Action));
  54017. BABYLON.StopAnimationAction = StopAnimationAction;
  54018. var DoNothingAction = /** @class */ (function (_super) {
  54019. __extends(DoNothingAction, _super);
  54020. function DoNothingAction(triggerOptions, condition) {
  54021. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54022. return _super.call(this, triggerOptions, condition) || this;
  54023. }
  54024. DoNothingAction.prototype.execute = function () {
  54025. };
  54026. DoNothingAction.prototype.serialize = function (parent) {
  54027. return _super.prototype._serialize.call(this, {
  54028. name: "DoNothingAction",
  54029. properties: []
  54030. }, parent);
  54031. };
  54032. return DoNothingAction;
  54033. }(BABYLON.Action));
  54034. BABYLON.DoNothingAction = DoNothingAction;
  54035. var CombineAction = /** @class */ (function (_super) {
  54036. __extends(CombineAction, _super);
  54037. function CombineAction(triggerOptions, children, condition) {
  54038. var _this = _super.call(this, triggerOptions, condition) || this;
  54039. _this.children = children;
  54040. return _this;
  54041. }
  54042. CombineAction.prototype._prepare = function () {
  54043. for (var index = 0; index < this.children.length; index++) {
  54044. this.children[index]._actionManager = this._actionManager;
  54045. this.children[index]._prepare();
  54046. }
  54047. };
  54048. CombineAction.prototype.execute = function (evt) {
  54049. for (var index = 0; index < this.children.length; index++) {
  54050. this.children[index].execute(evt);
  54051. }
  54052. };
  54053. CombineAction.prototype.serialize = function (parent) {
  54054. var serializationObject = _super.prototype._serialize.call(this, {
  54055. name: "CombineAction",
  54056. properties: [],
  54057. combine: []
  54058. }, parent);
  54059. for (var i = 0; i < this.children.length; i++) {
  54060. serializationObject.combine.push(this.children[i].serialize(null));
  54061. }
  54062. return serializationObject;
  54063. };
  54064. return CombineAction;
  54065. }(BABYLON.Action));
  54066. BABYLON.CombineAction = CombineAction;
  54067. var ExecuteCodeAction = /** @class */ (function (_super) {
  54068. __extends(ExecuteCodeAction, _super);
  54069. function ExecuteCodeAction(triggerOptions, func, condition) {
  54070. var _this = _super.call(this, triggerOptions, condition) || this;
  54071. _this.func = func;
  54072. return _this;
  54073. }
  54074. ExecuteCodeAction.prototype.execute = function (evt) {
  54075. this.func(evt);
  54076. };
  54077. return ExecuteCodeAction;
  54078. }(BABYLON.Action));
  54079. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54080. var SetParentAction = /** @class */ (function (_super) {
  54081. __extends(SetParentAction, _super);
  54082. function SetParentAction(triggerOptions, target, parent, condition) {
  54083. var _this = _super.call(this, triggerOptions, condition) || this;
  54084. _this._target = target;
  54085. _this._parent = parent;
  54086. return _this;
  54087. }
  54088. SetParentAction.prototype._prepare = function () {
  54089. };
  54090. SetParentAction.prototype.execute = function () {
  54091. if (this._target.parent === this._parent) {
  54092. return;
  54093. }
  54094. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54095. invertParentWorldMatrix.invert();
  54096. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54097. this._target.parent = this._parent;
  54098. };
  54099. SetParentAction.prototype.serialize = function (parent) {
  54100. return _super.prototype._serialize.call(this, {
  54101. name: "SetParentAction",
  54102. properties: [
  54103. BABYLON.Action._GetTargetProperty(this._target),
  54104. BABYLON.Action._GetTargetProperty(this._parent),
  54105. ]
  54106. }, parent);
  54107. };
  54108. return SetParentAction;
  54109. }(BABYLON.Action));
  54110. BABYLON.SetParentAction = SetParentAction;
  54111. var PlaySoundAction = /** @class */ (function (_super) {
  54112. __extends(PlaySoundAction, _super);
  54113. function PlaySoundAction(triggerOptions, sound, condition) {
  54114. var _this = _super.call(this, triggerOptions, condition) || this;
  54115. _this._sound = sound;
  54116. return _this;
  54117. }
  54118. PlaySoundAction.prototype._prepare = function () {
  54119. };
  54120. PlaySoundAction.prototype.execute = function () {
  54121. if (this._sound !== undefined)
  54122. this._sound.play();
  54123. };
  54124. PlaySoundAction.prototype.serialize = function (parent) {
  54125. return _super.prototype._serialize.call(this, {
  54126. name: "PlaySoundAction",
  54127. properties: [{ name: "sound", value: this._sound.name }]
  54128. }, parent);
  54129. };
  54130. return PlaySoundAction;
  54131. }(BABYLON.Action));
  54132. BABYLON.PlaySoundAction = PlaySoundAction;
  54133. var StopSoundAction = /** @class */ (function (_super) {
  54134. __extends(StopSoundAction, _super);
  54135. function StopSoundAction(triggerOptions, sound, condition) {
  54136. var _this = _super.call(this, triggerOptions, condition) || this;
  54137. _this._sound = sound;
  54138. return _this;
  54139. }
  54140. StopSoundAction.prototype._prepare = function () {
  54141. };
  54142. StopSoundAction.prototype.execute = function () {
  54143. if (this._sound !== undefined)
  54144. this._sound.stop();
  54145. };
  54146. StopSoundAction.prototype.serialize = function (parent) {
  54147. return _super.prototype._serialize.call(this, {
  54148. name: "StopSoundAction",
  54149. properties: [{ name: "sound", value: this._sound.name }]
  54150. }, parent);
  54151. };
  54152. return StopSoundAction;
  54153. }(BABYLON.Action));
  54154. BABYLON.StopSoundAction = StopSoundAction;
  54155. })(BABYLON || (BABYLON = {}));
  54156. //# sourceMappingURL=babylon.directActions.js.map
  54157. var BABYLON;
  54158. (function (BABYLON) {
  54159. var SpriteManager = /** @class */ (function () {
  54160. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54161. if (epsilon === void 0) { epsilon = 0.01; }
  54162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54163. this.name = name;
  54164. this.sprites = new Array();
  54165. this.renderingGroupId = 0;
  54166. this.layerMask = 0x0FFFFFFF;
  54167. this.fogEnabled = true;
  54168. this.isPickable = false;
  54169. /**
  54170. * An event triggered when the manager is disposed.
  54171. */
  54172. this.onDisposeObservable = new BABYLON.Observable();
  54173. this._vertexBuffers = {};
  54174. this._capacity = capacity;
  54175. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54176. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54177. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54178. if (cellSize.width && cellSize.height) {
  54179. this.cellWidth = cellSize.width;
  54180. this.cellHeight = cellSize.height;
  54181. }
  54182. else if (cellSize !== undefined) {
  54183. this.cellWidth = cellSize;
  54184. this.cellHeight = cellSize;
  54185. }
  54186. else {
  54187. return;
  54188. }
  54189. this._epsilon = epsilon;
  54190. this._scene = scene;
  54191. this._scene.spriteManagers.push(this);
  54192. var indices = [];
  54193. var index = 0;
  54194. for (var count = 0; count < capacity; count++) {
  54195. indices.push(index);
  54196. indices.push(index + 1);
  54197. indices.push(index + 2);
  54198. indices.push(index);
  54199. indices.push(index + 2);
  54200. indices.push(index + 3);
  54201. index += 4;
  54202. }
  54203. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54204. // VBO
  54205. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54206. this._vertexData = new Float32Array(capacity * 16 * 4);
  54207. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54208. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54209. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54210. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54211. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54212. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54213. this._vertexBuffers["options"] = options;
  54214. this._vertexBuffers["cellInfo"] = cellInfo;
  54215. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54216. // Effects
  54217. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54218. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54219. }
  54220. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54221. set: function (callback) {
  54222. if (this._onDisposeObserver) {
  54223. this.onDisposeObservable.remove(this._onDisposeObserver);
  54224. }
  54225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54226. },
  54227. enumerable: true,
  54228. configurable: true
  54229. });
  54230. Object.defineProperty(SpriteManager.prototype, "texture", {
  54231. get: function () {
  54232. return this._spriteTexture;
  54233. },
  54234. set: function (value) {
  54235. this._spriteTexture = value;
  54236. },
  54237. enumerable: true,
  54238. configurable: true
  54239. });
  54240. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54241. var arrayOffset = index * 16;
  54242. if (offsetX === 0)
  54243. offsetX = this._epsilon;
  54244. else if (offsetX === 1)
  54245. offsetX = 1 - this._epsilon;
  54246. if (offsetY === 0)
  54247. offsetY = this._epsilon;
  54248. else if (offsetY === 1)
  54249. offsetY = 1 - this._epsilon;
  54250. this._vertexData[arrayOffset] = sprite.position.x;
  54251. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54252. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54253. this._vertexData[arrayOffset + 3] = sprite.angle;
  54254. this._vertexData[arrayOffset + 4] = sprite.width;
  54255. this._vertexData[arrayOffset + 5] = sprite.height;
  54256. this._vertexData[arrayOffset + 6] = offsetX;
  54257. this._vertexData[arrayOffset + 7] = offsetY;
  54258. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54259. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54260. var offset = (sprite.cellIndex / rowSize) >> 0;
  54261. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54262. this._vertexData[arrayOffset + 11] = offset;
  54263. // Color
  54264. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54265. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54266. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54267. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54268. };
  54269. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54270. var count = Math.min(this._capacity, this.sprites.length);
  54271. var min = BABYLON.Vector3.Zero();
  54272. var max = BABYLON.Vector3.Zero();
  54273. var distance = Number.MAX_VALUE;
  54274. var currentSprite = null;
  54275. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54276. var cameraView = camera.getViewMatrix();
  54277. for (var index = 0; index < count; index++) {
  54278. var sprite = this.sprites[index];
  54279. if (!sprite) {
  54280. continue;
  54281. }
  54282. if (predicate) {
  54283. if (!predicate(sprite)) {
  54284. continue;
  54285. }
  54286. }
  54287. else if (!sprite.isPickable) {
  54288. continue;
  54289. }
  54290. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54291. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54292. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54293. if (ray.intersectsBoxMinMax(min, max)) {
  54294. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54295. if (distance > currentDistance) {
  54296. distance = currentDistance;
  54297. currentSprite = sprite;
  54298. if (fastCheck) {
  54299. break;
  54300. }
  54301. }
  54302. }
  54303. }
  54304. if (currentSprite) {
  54305. var result = new BABYLON.PickingInfo();
  54306. result.hit = true;
  54307. result.pickedSprite = currentSprite;
  54308. result.distance = distance;
  54309. return result;
  54310. }
  54311. return null;
  54312. };
  54313. SpriteManager.prototype.render = function () {
  54314. // Check
  54315. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54316. return;
  54317. var engine = this._scene.getEngine();
  54318. var baseSize = this._spriteTexture.getBaseSize();
  54319. // Sprites
  54320. var deltaTime = engine.getDeltaTime();
  54321. var max = Math.min(this._capacity, this.sprites.length);
  54322. var rowSize = baseSize.width / this.cellWidth;
  54323. var offset = 0;
  54324. for (var index = 0; index < max; index++) {
  54325. var sprite = this.sprites[index];
  54326. if (!sprite) {
  54327. continue;
  54328. }
  54329. sprite._animate(deltaTime);
  54330. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54331. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54332. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54333. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54334. }
  54335. this._buffer.update(this._vertexData);
  54336. // Render
  54337. var effect = this._effectBase;
  54338. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54339. effect = this._effectFog;
  54340. }
  54341. engine.enableEffect(effect);
  54342. var viewMatrix = this._scene.getViewMatrix();
  54343. effect.setTexture("diffuseSampler", this._spriteTexture);
  54344. effect.setMatrix("view", viewMatrix);
  54345. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54346. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54347. // Fog
  54348. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54349. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54350. effect.setColor3("vFogColor", this._scene.fogColor);
  54351. }
  54352. // VBOs
  54353. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54354. // Draw order
  54355. engine.setDepthFunctionToLessOrEqual();
  54356. effect.setBool("alphaTest", true);
  54357. engine.setColorWrite(false);
  54358. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54359. engine.setColorWrite(true);
  54360. effect.setBool("alphaTest", false);
  54361. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54362. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54364. };
  54365. SpriteManager.prototype.dispose = function () {
  54366. if (this._buffer) {
  54367. this._buffer.dispose();
  54368. this._buffer = null;
  54369. }
  54370. if (this._indexBuffer) {
  54371. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54372. this._indexBuffer = null;
  54373. }
  54374. if (this._spriteTexture) {
  54375. this._spriteTexture.dispose();
  54376. this._spriteTexture = null;
  54377. }
  54378. // Remove from scene
  54379. var index = this._scene.spriteManagers.indexOf(this);
  54380. this._scene.spriteManagers.splice(index, 1);
  54381. // Callback
  54382. this.onDisposeObservable.notifyObservers(this);
  54383. this.onDisposeObservable.clear();
  54384. };
  54385. return SpriteManager;
  54386. }());
  54387. BABYLON.SpriteManager = SpriteManager;
  54388. })(BABYLON || (BABYLON = {}));
  54389. //# sourceMappingURL=babylon.spriteManager.js.map
  54390. var BABYLON;
  54391. (function (BABYLON) {
  54392. var Sprite = /** @class */ (function () {
  54393. function Sprite(name, manager) {
  54394. this.name = name;
  54395. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54396. this.width = 1.0;
  54397. this.height = 1.0;
  54398. this.angle = 0;
  54399. this.cellIndex = 0;
  54400. this.invertU = 0;
  54401. this.invertV = 0;
  54402. this.animations = new Array();
  54403. this.isPickable = false;
  54404. this._animationStarted = false;
  54405. this._loopAnimation = false;
  54406. this._fromIndex = 0;
  54407. this._toIndex = 0;
  54408. this._delay = 0;
  54409. this._direction = 1;
  54410. this._time = 0;
  54411. this._manager = manager;
  54412. this._manager.sprites.push(this);
  54413. this.position = BABYLON.Vector3.Zero();
  54414. }
  54415. Object.defineProperty(Sprite.prototype, "size", {
  54416. get: function () {
  54417. return this.width;
  54418. },
  54419. set: function (value) {
  54420. this.width = value;
  54421. this.height = value;
  54422. },
  54423. enumerable: true,
  54424. configurable: true
  54425. });
  54426. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54427. this._fromIndex = from;
  54428. this._toIndex = to;
  54429. this._loopAnimation = loop;
  54430. this._delay = delay;
  54431. this._animationStarted = true;
  54432. this._direction = from < to ? 1 : -1;
  54433. this.cellIndex = from;
  54434. this._time = 0;
  54435. this._onAnimationEnd = onAnimationEnd;
  54436. };
  54437. Sprite.prototype.stopAnimation = function () {
  54438. this._animationStarted = false;
  54439. };
  54440. Sprite.prototype._animate = function (deltaTime) {
  54441. if (!this._animationStarted)
  54442. return;
  54443. this._time += deltaTime;
  54444. if (this._time > this._delay) {
  54445. this._time = this._time % this._delay;
  54446. this.cellIndex += this._direction;
  54447. if (this.cellIndex > this._toIndex) {
  54448. if (this._loopAnimation) {
  54449. this.cellIndex = this._fromIndex;
  54450. }
  54451. else {
  54452. this.cellIndex = this._toIndex;
  54453. this._animationStarted = false;
  54454. if (this._onAnimationEnd) {
  54455. this._onAnimationEnd();
  54456. }
  54457. if (this.disposeWhenFinishedAnimating) {
  54458. this.dispose();
  54459. }
  54460. }
  54461. }
  54462. }
  54463. };
  54464. Sprite.prototype.dispose = function () {
  54465. for (var i = 0; i < this._manager.sprites.length; i++) {
  54466. if (this._manager.sprites[i] == this) {
  54467. this._manager.sprites.splice(i, 1);
  54468. }
  54469. }
  54470. };
  54471. return Sprite;
  54472. }());
  54473. BABYLON.Sprite = Sprite;
  54474. })(BABYLON || (BABYLON = {}));
  54475. //# sourceMappingURL=babylon.sprite.js.map
  54476. var BABYLON;
  54477. (function (BABYLON) {
  54478. var IntersectionInfo = /** @class */ (function () {
  54479. function IntersectionInfo(bu, bv, distance) {
  54480. this.bu = bu;
  54481. this.bv = bv;
  54482. this.distance = distance;
  54483. this.faceId = 0;
  54484. this.subMeshId = 0;
  54485. }
  54486. return IntersectionInfo;
  54487. }());
  54488. BABYLON.IntersectionInfo = IntersectionInfo;
  54489. var PickingInfo = /** @class */ (function () {
  54490. function PickingInfo() {
  54491. this.hit = false;
  54492. this.distance = 0;
  54493. this.pickedPoint = null;
  54494. this.pickedMesh = null;
  54495. this.bu = 0;
  54496. this.bv = 0;
  54497. this.faceId = -1;
  54498. this.subMeshId = 0;
  54499. this.pickedSprite = null;
  54500. }
  54501. // Methods
  54502. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54503. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54504. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54505. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54506. return null;
  54507. }
  54508. var indices = this.pickedMesh.getIndices();
  54509. if (!indices) {
  54510. return null;
  54511. }
  54512. var result;
  54513. if (useVerticesNormals) {
  54514. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54515. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54516. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54517. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54518. normal0 = normal0.scale(this.bu);
  54519. normal1 = normal1.scale(this.bv);
  54520. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54521. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54522. }
  54523. else {
  54524. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54525. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54526. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54527. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54528. var p1p2 = vertex1.subtract(vertex2);
  54529. var p3p2 = vertex3.subtract(vertex2);
  54530. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54531. }
  54532. if (useWorldCoordinates) {
  54533. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54534. }
  54535. return BABYLON.Vector3.Normalize(result);
  54536. };
  54537. PickingInfo.prototype.getTextureCoordinates = function () {
  54538. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54539. return null;
  54540. }
  54541. var indices = this.pickedMesh.getIndices();
  54542. if (!indices) {
  54543. return null;
  54544. }
  54545. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54546. if (!uvs) {
  54547. return null;
  54548. }
  54549. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54550. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54551. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54552. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54553. uv1 = uv1.scale(this.bu);
  54554. uv2 = uv2.scale(this.bv);
  54555. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54556. };
  54557. return PickingInfo;
  54558. }());
  54559. BABYLON.PickingInfo = PickingInfo;
  54560. })(BABYLON || (BABYLON = {}));
  54561. //# sourceMappingURL=babylon.pickingInfo.js.map
  54562. var BABYLON;
  54563. (function (BABYLON) {
  54564. var Ray = /** @class */ (function () {
  54565. function Ray(origin, direction, length) {
  54566. if (length === void 0) { length = Number.MAX_VALUE; }
  54567. this.origin = origin;
  54568. this.direction = direction;
  54569. this.length = length;
  54570. }
  54571. // Methods
  54572. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54573. var d = 0.0;
  54574. var maxValue = Number.MAX_VALUE;
  54575. var inv;
  54576. var min;
  54577. var max;
  54578. var temp;
  54579. if (Math.abs(this.direction.x) < 0.0000001) {
  54580. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54581. return false;
  54582. }
  54583. }
  54584. else {
  54585. inv = 1.0 / this.direction.x;
  54586. min = (minimum.x - this.origin.x) * inv;
  54587. max = (maximum.x - this.origin.x) * inv;
  54588. if (max === -Infinity) {
  54589. max = Infinity;
  54590. }
  54591. if (min > max) {
  54592. temp = min;
  54593. min = max;
  54594. max = temp;
  54595. }
  54596. d = Math.max(min, d);
  54597. maxValue = Math.min(max, maxValue);
  54598. if (d > maxValue) {
  54599. return false;
  54600. }
  54601. }
  54602. if (Math.abs(this.direction.y) < 0.0000001) {
  54603. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54604. return false;
  54605. }
  54606. }
  54607. else {
  54608. inv = 1.0 / this.direction.y;
  54609. min = (minimum.y - this.origin.y) * inv;
  54610. max = (maximum.y - this.origin.y) * inv;
  54611. if (max === -Infinity) {
  54612. max = Infinity;
  54613. }
  54614. if (min > max) {
  54615. temp = min;
  54616. min = max;
  54617. max = temp;
  54618. }
  54619. d = Math.max(min, d);
  54620. maxValue = Math.min(max, maxValue);
  54621. if (d > maxValue) {
  54622. return false;
  54623. }
  54624. }
  54625. if (Math.abs(this.direction.z) < 0.0000001) {
  54626. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54627. return false;
  54628. }
  54629. }
  54630. else {
  54631. inv = 1.0 / this.direction.z;
  54632. min = (minimum.z - this.origin.z) * inv;
  54633. max = (maximum.z - this.origin.z) * inv;
  54634. if (max === -Infinity) {
  54635. max = Infinity;
  54636. }
  54637. if (min > max) {
  54638. temp = min;
  54639. min = max;
  54640. max = temp;
  54641. }
  54642. d = Math.max(min, d);
  54643. maxValue = Math.min(max, maxValue);
  54644. if (d > maxValue) {
  54645. return false;
  54646. }
  54647. }
  54648. return true;
  54649. };
  54650. Ray.prototype.intersectsBox = function (box) {
  54651. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54652. };
  54653. Ray.prototype.intersectsSphere = function (sphere) {
  54654. var x = sphere.center.x - this.origin.x;
  54655. var y = sphere.center.y - this.origin.y;
  54656. var z = sphere.center.z - this.origin.z;
  54657. var pyth = (x * x) + (y * y) + (z * z);
  54658. var rr = sphere.radius * sphere.radius;
  54659. if (pyth <= rr) {
  54660. return true;
  54661. }
  54662. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54663. if (dot < 0.0) {
  54664. return false;
  54665. }
  54666. var temp = pyth - (dot * dot);
  54667. return temp <= rr;
  54668. };
  54669. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54670. if (!this._edge1) {
  54671. this._edge1 = BABYLON.Vector3.Zero();
  54672. this._edge2 = BABYLON.Vector3.Zero();
  54673. this._pvec = BABYLON.Vector3.Zero();
  54674. this._tvec = BABYLON.Vector3.Zero();
  54675. this._qvec = BABYLON.Vector3.Zero();
  54676. }
  54677. vertex1.subtractToRef(vertex0, this._edge1);
  54678. vertex2.subtractToRef(vertex0, this._edge2);
  54679. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54680. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54681. if (det === 0) {
  54682. return null;
  54683. }
  54684. var invdet = 1 / det;
  54685. this.origin.subtractToRef(vertex0, this._tvec);
  54686. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54687. if (bu < 0 || bu > 1.0) {
  54688. return null;
  54689. }
  54690. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54691. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54692. if (bv < 0 || bu + bv > 1.0) {
  54693. return null;
  54694. }
  54695. //check if the distance is longer than the predefined length.
  54696. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54697. if (distance > this.length) {
  54698. return null;
  54699. }
  54700. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54701. };
  54702. Ray.prototype.intersectsPlane = function (plane) {
  54703. var distance;
  54704. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54705. if (Math.abs(result1) < 9.99999997475243E-07) {
  54706. return null;
  54707. }
  54708. else {
  54709. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54710. distance = (-plane.d - result2) / result1;
  54711. if (distance < 0.0) {
  54712. if (distance < -9.99999997475243E-07) {
  54713. return null;
  54714. }
  54715. else {
  54716. return 0;
  54717. }
  54718. }
  54719. return distance;
  54720. }
  54721. };
  54722. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54723. var tm = BABYLON.Tmp.Matrix[0];
  54724. mesh.getWorldMatrix().invertToRef(tm);
  54725. if (this._tmpRay) {
  54726. Ray.TransformToRef(this, tm, this._tmpRay);
  54727. }
  54728. else {
  54729. this._tmpRay = Ray.Transform(this, tm);
  54730. }
  54731. return mesh.intersects(this._tmpRay, fastCheck);
  54732. };
  54733. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54734. if (results) {
  54735. results.length = 0;
  54736. }
  54737. else {
  54738. results = [];
  54739. }
  54740. for (var i = 0; i < meshes.length; i++) {
  54741. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54742. if (pickInfo.hit) {
  54743. results.push(pickInfo);
  54744. }
  54745. }
  54746. results.sort(this._comparePickingInfo);
  54747. return results;
  54748. };
  54749. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54750. if (pickingInfoA.distance < pickingInfoB.distance) {
  54751. return -1;
  54752. }
  54753. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54754. return 1;
  54755. }
  54756. else {
  54757. return 0;
  54758. }
  54759. };
  54760. /**
  54761. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54762. * @param sega the first point of the segment to test the intersection against
  54763. * @param segb the second point of the segment to test the intersection against
  54764. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54765. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54766. */
  54767. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54768. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54769. var u = segb.subtract(sega);
  54770. var v = rsegb.subtract(this.origin);
  54771. var w = sega.subtract(this.origin);
  54772. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54773. var b = BABYLON.Vector3.Dot(u, v);
  54774. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54775. var d = BABYLON.Vector3.Dot(u, w);
  54776. var e = BABYLON.Vector3.Dot(v, w);
  54777. var D = a * c - b * b; // always >= 0
  54778. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54779. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54780. // compute the line parameters of the two closest points
  54781. if (D < Ray.smallnum) { // the lines are almost parallel
  54782. sN = 0.0; // force using point P0 on segment S1
  54783. sD = 1.0; // to prevent possible division by 0.0 later
  54784. tN = e;
  54785. tD = c;
  54786. }
  54787. else { // get the closest points on the infinite lines
  54788. sN = (b * e - c * d);
  54789. tN = (a * e - b * d);
  54790. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54791. sN = 0.0;
  54792. tN = e;
  54793. tD = c;
  54794. }
  54795. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54796. sN = sD;
  54797. tN = e + b;
  54798. tD = c;
  54799. }
  54800. }
  54801. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54802. tN = 0.0;
  54803. // recompute sc for this edge
  54804. if (-d < 0.0) {
  54805. sN = 0.0;
  54806. }
  54807. else if (-d > a)
  54808. sN = sD;
  54809. else {
  54810. sN = -d;
  54811. sD = a;
  54812. }
  54813. }
  54814. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54815. tN = tD;
  54816. // recompute sc for this edge
  54817. if ((-d + b) < 0.0) {
  54818. sN = 0;
  54819. }
  54820. else if ((-d + b) > a) {
  54821. sN = sD;
  54822. }
  54823. else {
  54824. sN = (-d + b);
  54825. sD = a;
  54826. }
  54827. }
  54828. // finally do the division to get sc and tc
  54829. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54830. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54831. // get the difference of the two closest points
  54832. var qtc = v.multiplyByFloats(tc, tc, tc);
  54833. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54834. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54835. if (isIntersected) {
  54836. return qtc.length();
  54837. }
  54838. return -1;
  54839. };
  54840. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54841. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54842. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54843. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54844. this.direction.normalize();
  54845. return this;
  54846. };
  54847. // Statics
  54848. Ray.Zero = function () {
  54849. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54850. };
  54851. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54852. var result = Ray.Zero();
  54853. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54854. };
  54855. /**
  54856. * 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
  54857. * transformed to the given world matrix.
  54858. * @param origin The origin point
  54859. * @param end The end point
  54860. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54861. */
  54862. Ray.CreateNewFromTo = function (origin, end, world) {
  54863. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54864. var direction = end.subtract(origin);
  54865. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54866. direction.normalize();
  54867. return Ray.Transform(new Ray(origin, direction, length), world);
  54868. };
  54869. Ray.Transform = function (ray, matrix) {
  54870. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54871. Ray.TransformToRef(ray, matrix, result);
  54872. return result;
  54873. };
  54874. Ray.TransformToRef = function (ray, matrix, result) {
  54875. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54876. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54877. result.length = ray.length;
  54878. var dir = result.direction;
  54879. var len = dir.length();
  54880. if (!(len === 0 || len === 1)) {
  54881. var num = 1.0 / len;
  54882. dir.x *= num;
  54883. dir.y *= num;
  54884. dir.z *= num;
  54885. result.length *= len;
  54886. }
  54887. };
  54888. Ray.smallnum = 0.00000001;
  54889. Ray.rayl = 10e8;
  54890. return Ray;
  54891. }());
  54892. BABYLON.Ray = Ray;
  54893. })(BABYLON || (BABYLON = {}));
  54894. //# sourceMappingURL=babylon.ray.js.map
  54895. var BABYLON;
  54896. (function (BABYLON) {
  54897. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54898. if (boxMin.x > sphereCenter.x + sphereRadius)
  54899. return false;
  54900. if (sphereCenter.x - sphereRadius > boxMax.x)
  54901. return false;
  54902. if (boxMin.y > sphereCenter.y + sphereRadius)
  54903. return false;
  54904. if (sphereCenter.y - sphereRadius > boxMax.y)
  54905. return false;
  54906. if (boxMin.z > sphereCenter.z + sphereRadius)
  54907. return false;
  54908. if (sphereCenter.z - sphereRadius > boxMax.z)
  54909. return false;
  54910. return true;
  54911. };
  54912. var getLowestRoot = (function () {
  54913. var result = { root: 0, found: false };
  54914. return function (a, b, c, maxR) {
  54915. result.root = 0;
  54916. result.found = false;
  54917. var determinant = b * b - 4.0 * a * c;
  54918. if (determinant < 0)
  54919. return result;
  54920. var sqrtD = Math.sqrt(determinant);
  54921. var r1 = (-b - sqrtD) / (2.0 * a);
  54922. var r2 = (-b + sqrtD) / (2.0 * a);
  54923. if (r1 > r2) {
  54924. var temp = r2;
  54925. r2 = r1;
  54926. r1 = temp;
  54927. }
  54928. if (r1 > 0 && r1 < maxR) {
  54929. result.root = r1;
  54930. result.found = true;
  54931. return result;
  54932. }
  54933. if (r2 > 0 && r2 < maxR) {
  54934. result.root = r2;
  54935. result.found = true;
  54936. return result;
  54937. }
  54938. return result;
  54939. };
  54940. })();
  54941. var Collider = /** @class */ (function () {
  54942. function Collider() {
  54943. this._collisionPoint = BABYLON.Vector3.Zero();
  54944. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54945. this._tempVector = BABYLON.Vector3.Zero();
  54946. this._tempVector2 = BABYLON.Vector3.Zero();
  54947. this._tempVector3 = BABYLON.Vector3.Zero();
  54948. this._tempVector4 = BABYLON.Vector3.Zero();
  54949. this._edge = BABYLON.Vector3.Zero();
  54950. this._baseToVertex = BABYLON.Vector3.Zero();
  54951. this._destinationPoint = BABYLON.Vector3.Zero();
  54952. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54953. this._displacementVector = BABYLON.Vector3.Zero();
  54954. this._radius = BABYLON.Vector3.One();
  54955. this._retry = 0;
  54956. this._basePointWorld = BABYLON.Vector3.Zero();
  54957. this._velocityWorld = BABYLON.Vector3.Zero();
  54958. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54959. this._collisionMask = -1;
  54960. }
  54961. Object.defineProperty(Collider.prototype, "collisionMask", {
  54962. get: function () {
  54963. return this._collisionMask;
  54964. },
  54965. set: function (mask) {
  54966. this._collisionMask = !isNaN(mask) ? mask : -1;
  54967. },
  54968. enumerable: true,
  54969. configurable: true
  54970. });
  54971. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54972. /**
  54973. * Gets the plane normal used to compute the sliding response (in local space)
  54974. */
  54975. get: function () {
  54976. return this._slidePlaneNormal;
  54977. },
  54978. enumerable: true,
  54979. configurable: true
  54980. });
  54981. // Methods
  54982. Collider.prototype._initialize = function (source, dir, e) {
  54983. this._velocity = dir;
  54984. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54985. this._basePoint = source;
  54986. source.multiplyToRef(this._radius, this._basePointWorld);
  54987. dir.multiplyToRef(this._radius, this._velocityWorld);
  54988. this._velocityWorldLength = this._velocityWorld.length();
  54989. this._epsilon = e;
  54990. this.collisionFound = false;
  54991. };
  54992. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54993. pa.subtractToRef(point, this._tempVector);
  54994. pb.subtractToRef(point, this._tempVector2);
  54995. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54996. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54997. if (d < 0)
  54998. return false;
  54999. pc.subtractToRef(point, this._tempVector3);
  55000. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55001. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55002. if (d < 0)
  55003. return false;
  55004. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55005. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55006. return d >= 0;
  55007. };
  55008. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55009. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55010. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55011. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55012. return false;
  55013. }
  55014. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55015. return false;
  55016. return true;
  55017. };
  55018. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55019. var t0;
  55020. var embeddedInPlane = false;
  55021. //defensive programming, actually not needed.
  55022. if (!trianglePlaneArray) {
  55023. trianglePlaneArray = [];
  55024. }
  55025. if (!trianglePlaneArray[faceIndex]) {
  55026. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55027. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55028. }
  55029. var trianglePlane = trianglePlaneArray[faceIndex];
  55030. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55031. return;
  55032. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55033. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55034. if (normalDotVelocity == 0) {
  55035. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55036. return;
  55037. embeddedInPlane = true;
  55038. t0 = 0;
  55039. }
  55040. else {
  55041. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55042. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55043. if (t0 > t1) {
  55044. var temp = t1;
  55045. t1 = t0;
  55046. t0 = temp;
  55047. }
  55048. if (t0 > 1.0 || t1 < 0.0)
  55049. return;
  55050. if (t0 < 0)
  55051. t0 = 0;
  55052. if (t0 > 1.0)
  55053. t0 = 1.0;
  55054. }
  55055. this._collisionPoint.copyFromFloats(0, 0, 0);
  55056. var found = false;
  55057. var t = 1.0;
  55058. if (!embeddedInPlane) {
  55059. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55060. this._velocity.scaleToRef(t0, this._tempVector);
  55061. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55062. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55063. found = true;
  55064. t = t0;
  55065. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55066. }
  55067. }
  55068. if (!found) {
  55069. var velocitySquaredLength = this._velocity.lengthSquared();
  55070. var a = velocitySquaredLength;
  55071. this._basePoint.subtractToRef(p1, this._tempVector);
  55072. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55073. var c = this._tempVector.lengthSquared() - 1.0;
  55074. var lowestRoot = getLowestRoot(a, b, c, t);
  55075. if (lowestRoot.found) {
  55076. t = lowestRoot.root;
  55077. found = true;
  55078. this._collisionPoint.copyFrom(p1);
  55079. }
  55080. this._basePoint.subtractToRef(p2, this._tempVector);
  55081. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55082. c = this._tempVector.lengthSquared() - 1.0;
  55083. lowestRoot = getLowestRoot(a, b, c, t);
  55084. if (lowestRoot.found) {
  55085. t = lowestRoot.root;
  55086. found = true;
  55087. this._collisionPoint.copyFrom(p2);
  55088. }
  55089. this._basePoint.subtractToRef(p3, this._tempVector);
  55090. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55091. c = this._tempVector.lengthSquared() - 1.0;
  55092. lowestRoot = getLowestRoot(a, b, c, t);
  55093. if (lowestRoot.found) {
  55094. t = lowestRoot.root;
  55095. found = true;
  55096. this._collisionPoint.copyFrom(p3);
  55097. }
  55098. p2.subtractToRef(p1, this._edge);
  55099. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55100. var edgeSquaredLength = this._edge.lengthSquared();
  55101. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55102. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55103. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55104. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55105. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55106. lowestRoot = getLowestRoot(a, b, c, t);
  55107. if (lowestRoot.found) {
  55108. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55109. if (f >= 0.0 && f <= 1.0) {
  55110. t = lowestRoot.root;
  55111. found = true;
  55112. this._edge.scaleInPlace(f);
  55113. p1.addToRef(this._edge, this._collisionPoint);
  55114. }
  55115. }
  55116. p3.subtractToRef(p2, this._edge);
  55117. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55118. edgeSquaredLength = this._edge.lengthSquared();
  55119. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55120. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55121. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55122. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55123. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55124. lowestRoot = getLowestRoot(a, b, c, t);
  55125. if (lowestRoot.found) {
  55126. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55127. if (f >= 0.0 && f <= 1.0) {
  55128. t = lowestRoot.root;
  55129. found = true;
  55130. this._edge.scaleInPlace(f);
  55131. p2.addToRef(this._edge, this._collisionPoint);
  55132. }
  55133. }
  55134. p1.subtractToRef(p3, this._edge);
  55135. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55136. edgeSquaredLength = this._edge.lengthSquared();
  55137. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55138. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55139. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55140. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55141. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55142. lowestRoot = getLowestRoot(a, b, c, t);
  55143. if (lowestRoot.found) {
  55144. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55145. if (f >= 0.0 && f <= 1.0) {
  55146. t = lowestRoot.root;
  55147. found = true;
  55148. this._edge.scaleInPlace(f);
  55149. p3.addToRef(this._edge, this._collisionPoint);
  55150. }
  55151. }
  55152. }
  55153. if (found) {
  55154. var distToCollision = t * this._velocity.length();
  55155. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55156. if (!this.intersectionPoint) {
  55157. this.intersectionPoint = this._collisionPoint.clone();
  55158. }
  55159. else {
  55160. this.intersectionPoint.copyFrom(this._collisionPoint);
  55161. }
  55162. this._nearestDistance = distToCollision;
  55163. this.collisionFound = true;
  55164. }
  55165. }
  55166. };
  55167. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55168. for (var i = indexStart; i < indexEnd; i += 3) {
  55169. var p1 = pts[indices[i] - decal];
  55170. var p2 = pts[indices[i + 1] - decal];
  55171. var p3 = pts[indices[i + 2] - decal];
  55172. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55173. }
  55174. };
  55175. Collider.prototype._getResponse = function (pos, vel) {
  55176. pos.addToRef(vel, this._destinationPoint);
  55177. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55178. this._basePoint.addToRef(vel, pos);
  55179. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55180. this._slidePlaneNormal.normalize();
  55181. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55182. pos.addInPlace(this._displacementVector);
  55183. this.intersectionPoint.addInPlace(this._displacementVector);
  55184. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55185. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55186. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55187. };
  55188. return Collider;
  55189. }());
  55190. BABYLON.Collider = Collider;
  55191. })(BABYLON || (BABYLON = {}));
  55192. //# sourceMappingURL=babylon.collider.js.map
  55193. var BABYLON;
  55194. (function (BABYLON) {
  55195. //WebWorker code will be inserted to this variable.
  55196. BABYLON.CollisionWorker = "";
  55197. /** Defines supported task for worker process */
  55198. var WorkerTaskType;
  55199. (function (WorkerTaskType) {
  55200. /** Initialization */
  55201. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55202. /** Update of geometry */
  55203. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55204. /** Evaluate collision */
  55205. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55206. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55207. /** Defines kind of replies returned by worker */
  55208. var WorkerReplyType;
  55209. (function (WorkerReplyType) {
  55210. /** Success */
  55211. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55212. /** Unkown error */
  55213. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55214. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55215. var CollisionCoordinatorWorker = /** @class */ (function () {
  55216. function CollisionCoordinatorWorker() {
  55217. var _this = this;
  55218. this._scaledPosition = BABYLON.Vector3.Zero();
  55219. this._scaledVelocity = BABYLON.Vector3.Zero();
  55220. this.onMeshUpdated = function (transformNode) {
  55221. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55222. };
  55223. this.onGeometryUpdated = function (geometry) {
  55224. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55225. };
  55226. this._afterRender = function () {
  55227. if (!_this._init)
  55228. return;
  55229. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55230. return;
  55231. }
  55232. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55233. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55234. if (_this._runningUpdated > 4) {
  55235. return;
  55236. }
  55237. ++_this._runningUpdated;
  55238. var payload = {
  55239. updatedMeshes: _this._addUpdateMeshesList,
  55240. updatedGeometries: _this._addUpdateGeometriesList,
  55241. removedGeometries: _this._toRemoveGeometryArray,
  55242. removedMeshes: _this._toRemoveMeshesArray
  55243. };
  55244. var message = {
  55245. payload: payload,
  55246. taskType: WorkerTaskType.UPDATE
  55247. };
  55248. var serializable = [];
  55249. for (var id in payload.updatedGeometries) {
  55250. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55251. //prepare transferables
  55252. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55253. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55254. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55255. }
  55256. }
  55257. _this._worker.postMessage(message, serializable);
  55258. _this._addUpdateMeshesList = {};
  55259. _this._addUpdateGeometriesList = {};
  55260. _this._toRemoveGeometryArray = [];
  55261. _this._toRemoveMeshesArray = [];
  55262. };
  55263. this._onMessageFromWorker = function (e) {
  55264. var returnData = e.data;
  55265. if (returnData.error != WorkerReplyType.SUCCESS) {
  55266. //TODO what errors can be returned from the worker?
  55267. BABYLON.Tools.Warn("error returned from worker!");
  55268. return;
  55269. }
  55270. switch (returnData.taskType) {
  55271. case WorkerTaskType.INIT:
  55272. _this._init = true;
  55273. //Update the worked with ALL of the scene's current state
  55274. _this._scene.meshes.forEach(function (mesh) {
  55275. _this.onMeshAdded(mesh);
  55276. });
  55277. _this._scene.getGeometries().forEach(function (geometry) {
  55278. _this.onGeometryAdded(geometry);
  55279. });
  55280. break;
  55281. case WorkerTaskType.UPDATE:
  55282. _this._runningUpdated--;
  55283. break;
  55284. case WorkerTaskType.COLLIDE:
  55285. var returnPayload = returnData.payload;
  55286. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55287. return;
  55288. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55289. if (callback) {
  55290. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55291. if (mesh) {
  55292. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55293. }
  55294. }
  55295. //cleanup
  55296. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55297. break;
  55298. }
  55299. };
  55300. this._collisionsCallbackArray = [];
  55301. this._init = false;
  55302. this._runningUpdated = 0;
  55303. this._addUpdateMeshesList = {};
  55304. this._addUpdateGeometriesList = {};
  55305. this._toRemoveGeometryArray = [];
  55306. this._toRemoveMeshesArray = [];
  55307. }
  55308. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55309. if (!this._init)
  55310. return;
  55311. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55312. return;
  55313. position.divideToRef(collider._radius, this._scaledPosition);
  55314. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55315. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55316. var payload = {
  55317. collider: {
  55318. position: this._scaledPosition.asArray(),
  55319. velocity: this._scaledVelocity.asArray(),
  55320. radius: collider._radius.asArray()
  55321. },
  55322. collisionId: collisionIndex,
  55323. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55324. maximumRetry: maximumRetry
  55325. };
  55326. var message = {
  55327. payload: payload,
  55328. taskType: WorkerTaskType.COLLIDE
  55329. };
  55330. this._worker.postMessage(message);
  55331. };
  55332. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55333. this._scene = scene;
  55334. this._scene.registerAfterRender(this._afterRender);
  55335. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55336. this._worker = new Worker(workerUrl);
  55337. this._worker.onmessage = this._onMessageFromWorker;
  55338. var message = {
  55339. payload: {},
  55340. taskType: WorkerTaskType.INIT
  55341. };
  55342. this._worker.postMessage(message);
  55343. };
  55344. CollisionCoordinatorWorker.prototype.destroy = function () {
  55345. this._scene.unregisterAfterRender(this._afterRender);
  55346. this._worker.terminate();
  55347. };
  55348. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55349. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55350. this.onMeshUpdated(mesh);
  55351. };
  55352. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55353. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55354. };
  55355. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55356. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55357. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55358. this.onGeometryUpdated(geometry);
  55359. };
  55360. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55361. this._toRemoveGeometryArray.push(geometry.id);
  55362. };
  55363. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55364. var submeshes = [];
  55365. if (mesh.subMeshes) {
  55366. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55367. var boundingInfo = sm.getBoundingInfo();
  55368. return {
  55369. position: idx,
  55370. verticesStart: sm.verticesStart,
  55371. verticesCount: sm.verticesCount,
  55372. indexStart: sm.indexStart,
  55373. indexCount: sm.indexCount,
  55374. hasMaterial: !!sm.getMaterial(),
  55375. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55376. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55377. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55378. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55379. };
  55380. });
  55381. }
  55382. var geometryId = null;
  55383. if (mesh instanceof BABYLON.Mesh) {
  55384. var geometry = mesh.geometry;
  55385. geometryId = geometry ? geometry.id : null;
  55386. }
  55387. else if (mesh instanceof BABYLON.InstancedMesh) {
  55388. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55389. geometryId = geometry ? geometry.id : null;
  55390. }
  55391. var boundingInfo = mesh.getBoundingInfo();
  55392. return {
  55393. uniqueId: mesh.uniqueId,
  55394. id: mesh.id,
  55395. name: mesh.name,
  55396. geometryId: geometryId,
  55397. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55398. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55399. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55400. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55401. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55402. subMeshes: submeshes,
  55403. checkCollisions: mesh.checkCollisions
  55404. };
  55405. };
  55406. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55407. return {
  55408. id: geometry.id,
  55409. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55410. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55411. indices: new Uint32Array(geometry.getIndices() || []),
  55412. };
  55413. };
  55414. return CollisionCoordinatorWorker;
  55415. }());
  55416. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55417. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55418. function CollisionCoordinatorLegacy() {
  55419. this._scaledPosition = BABYLON.Vector3.Zero();
  55420. this._scaledVelocity = BABYLON.Vector3.Zero();
  55421. this._finalPosition = BABYLON.Vector3.Zero();
  55422. }
  55423. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55424. position.divideToRef(collider._radius, this._scaledPosition);
  55425. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55426. collider.collidedMesh = null;
  55427. collider._retry = 0;
  55428. collider._initialVelocity = this._scaledVelocity;
  55429. collider._initialPosition = this._scaledPosition;
  55430. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55431. this._finalPosition.multiplyInPlace(collider._radius);
  55432. //run the callback
  55433. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55434. };
  55435. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55436. this._scene = scene;
  55437. };
  55438. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55439. //Legacy need no destruction method.
  55440. };
  55441. //No update in legacy mode
  55442. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55443. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55444. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55445. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55446. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55447. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55448. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55449. if (excludedMesh === void 0) { excludedMesh = null; }
  55450. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55451. if (collider._retry >= maximumRetry) {
  55452. finalPosition.copyFrom(position);
  55453. return;
  55454. }
  55455. // Check if this is a mesh else camera or -1
  55456. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55457. collider._initialize(position, velocity, closeDistance);
  55458. // Check all meshes
  55459. for (var index = 0; index < this._scene.meshes.length; index++) {
  55460. var mesh = this._scene.meshes[index];
  55461. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55462. mesh._checkCollision(collider);
  55463. }
  55464. }
  55465. if (!collider.collisionFound) {
  55466. position.addToRef(velocity, finalPosition);
  55467. return;
  55468. }
  55469. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55470. collider._getResponse(position, velocity);
  55471. }
  55472. if (velocity.length() <= closeDistance) {
  55473. finalPosition.copyFrom(position);
  55474. return;
  55475. }
  55476. collider._retry++;
  55477. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55478. };
  55479. return CollisionCoordinatorLegacy;
  55480. }());
  55481. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55482. })(BABYLON || (BABYLON = {}));
  55483. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55484. var BABYLON;
  55485. (function (BABYLON) {
  55486. /**
  55487. * A particle represents one of the element emitted by a particle system.
  55488. * This is mainly define by its coordinates, direction, velocity and age.
  55489. */
  55490. var Particle = /** @class */ (function () {
  55491. /**
  55492. * Creates a new instance Particle
  55493. * @param particleSystem the particle system the particle belongs to
  55494. */
  55495. function Particle(
  55496. /**
  55497. * particleSystem the particle system the particle belongs to.
  55498. */
  55499. particleSystem) {
  55500. this.particleSystem = particleSystem;
  55501. /**
  55502. * The world position of the particle in the scene.
  55503. */
  55504. this.position = BABYLON.Vector3.Zero();
  55505. /**
  55506. * The world direction of the particle in the scene.
  55507. */
  55508. this.direction = BABYLON.Vector3.Zero();
  55509. /**
  55510. * The color of the particle.
  55511. */
  55512. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55513. /**
  55514. * The color change of the particle per step.
  55515. */
  55516. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55517. /**
  55518. * Defines how long will the life of the particle be.
  55519. */
  55520. this.lifeTime = 1.0;
  55521. /**
  55522. * The current age of the particle.
  55523. */
  55524. this.age = 0;
  55525. /**
  55526. * The current size of the particle.
  55527. */
  55528. this.size = 0;
  55529. /**
  55530. * The current angle of the particle.
  55531. */
  55532. this.angle = 0;
  55533. /**
  55534. * Defines how fast is the angle changing.
  55535. */
  55536. this.angularSpeed = 0;
  55537. /**
  55538. * Defines the cell index used by the particle to be rendered from a sprite.
  55539. */
  55540. this.cellIndex = 0;
  55541. this._currentFrameCounter = 0;
  55542. if (!this.particleSystem.isAnimationSheetEnabled) {
  55543. return;
  55544. }
  55545. this.updateCellInfoFromSystem();
  55546. }
  55547. Particle.prototype.updateCellInfoFromSystem = function () {
  55548. this.cellIndex = this.particleSystem.startSpriteCellID;
  55549. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55550. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55551. }
  55552. else {
  55553. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55554. }
  55555. };
  55556. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55557. // (ageOffset / scaledUpdateSpeed) / available cells
  55558. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55559. this._currentFrameCounter += scaledUpdateSpeed;
  55560. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55561. this._currentFrameCounter = 0;
  55562. this.cellIndex++;
  55563. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55564. this.cellIndex = this.particleSystem.endSpriteCellID;
  55565. }
  55566. }
  55567. };
  55568. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55569. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55570. this.cellIndex++;
  55571. this._currentFrameCounter = 0;
  55572. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55573. if (this.particleSystem.spriteCellLoop) {
  55574. this.cellIndex = this.particleSystem.startSpriteCellID;
  55575. }
  55576. else {
  55577. this.cellIndex = this.particleSystem.endSpriteCellID;
  55578. }
  55579. }
  55580. }
  55581. else {
  55582. this._currentFrameCounter++;
  55583. }
  55584. };
  55585. /**
  55586. * Copy the properties of particle to another one.
  55587. * @param other the particle to copy the information to.
  55588. */
  55589. Particle.prototype.copyTo = function (other) {
  55590. other.position.copyFrom(this.position);
  55591. other.direction.copyFrom(this.direction);
  55592. other.color.copyFrom(this.color);
  55593. other.colorStep.copyFrom(this.colorStep);
  55594. other.lifeTime = this.lifeTime;
  55595. other.age = this.age;
  55596. other.size = this.size;
  55597. other.angle = this.angle;
  55598. other.angularSpeed = this.angularSpeed;
  55599. other.particleSystem = this.particleSystem;
  55600. other.cellIndex = this.cellIndex;
  55601. };
  55602. return Particle;
  55603. }());
  55604. BABYLON.Particle = Particle;
  55605. })(BABYLON || (BABYLON = {}));
  55606. //# sourceMappingURL=babylon.particle.js.map
  55607. var BABYLON;
  55608. (function (BABYLON) {
  55609. /**
  55610. * This represents a particle system in Babylon.
  55611. * 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.
  55612. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55613. * @example https://doc.babylonjs.com/babylon101/particles
  55614. */
  55615. var ParticleSystem = /** @class */ (function () {
  55616. /**
  55617. * Instantiates a particle system.
  55618. * 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.
  55619. * @param name The name of the particle system
  55620. * @param capacity The max number of particles alive at the same time
  55621. * @param scene The scene the particle system belongs to
  55622. * @param customEffect a custom effect used to change the way particles are rendered by default
  55623. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55624. * @param epsilon Offset used to render the particles
  55625. */
  55626. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55627. if (customEffect === void 0) { customEffect = null; }
  55628. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55629. if (epsilon === void 0) { epsilon = 0.01; }
  55630. var _this = this;
  55631. /**
  55632. * List of animations used by the particle system.
  55633. */
  55634. this.animations = [];
  55635. /**
  55636. * The rendering group used by the Particle system to chose when to render.
  55637. */
  55638. this.renderingGroupId = 0;
  55639. /**
  55640. * The emitter represents the Mesh or position we are attaching the particle system to.
  55641. */
  55642. this.emitter = null;
  55643. /**
  55644. * The maximum number of particles to emit per frame
  55645. */
  55646. this.emitRate = 10;
  55647. /**
  55648. * If you want to launch only a few particles at once, that can be done, as well.
  55649. */
  55650. this.manualEmitCount = -1;
  55651. /**
  55652. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55653. */
  55654. this.updateSpeed = 0.01;
  55655. /**
  55656. * The amount of time the particle system is running (depends of the overall update speed).
  55657. */
  55658. this.targetStopDuration = 0;
  55659. /**
  55660. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55661. */
  55662. this.disposeOnStop = false;
  55663. /**
  55664. * Minimum power of emitting particles.
  55665. */
  55666. this.minEmitPower = 1;
  55667. /**
  55668. * Maximum power of emitting particles.
  55669. */
  55670. this.maxEmitPower = 1;
  55671. /**
  55672. * Minimum life time of emitting particles.
  55673. */
  55674. this.minLifeTime = 1;
  55675. /**
  55676. * Maximum life time of emitting particles.
  55677. */
  55678. this.maxLifeTime = 1;
  55679. /**
  55680. * Minimum Size of emitting particles.
  55681. */
  55682. this.minSize = 1;
  55683. /**
  55684. * Maximum Size of emitting particles.
  55685. */
  55686. this.maxSize = 1;
  55687. /**
  55688. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55689. */
  55690. this.minAngularSpeed = 0;
  55691. /**
  55692. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55693. */
  55694. this.maxAngularSpeed = 0;
  55695. /**
  55696. * The layer mask we are rendering the particles through.
  55697. */
  55698. this.layerMask = 0x0FFFFFFF;
  55699. /**
  55700. * This can help using your own shader to render the particle system.
  55701. * The according effect will be created
  55702. */
  55703. this.customShader = null;
  55704. /**
  55705. * By default particle system starts as soon as they are created. This prevents the
  55706. * automatic start to happen and let you decide when to start emitting particles.
  55707. */
  55708. this.preventAutoStart = false;
  55709. /**
  55710. * Callback triggered when the particle animation is ending.
  55711. */
  55712. this.onAnimationEnd = null;
  55713. /**
  55714. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55715. */
  55716. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55717. /**
  55718. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55719. * to override the particles.
  55720. */
  55721. this.forceDepthWrite = false;
  55722. /**
  55723. * You can use gravity if you want to give an orientation to your particles.
  55724. */
  55725. this.gravity = BABYLON.Vector3.Zero();
  55726. /**
  55727. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55728. */
  55729. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55730. /**
  55731. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55732. */
  55733. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55734. /**
  55735. * Color the particle will have at the end of its lifetime.
  55736. */
  55737. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55738. /**
  55739. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55740. */
  55741. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55742. /**
  55743. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55744. */
  55745. this.spriteCellLoop = true;
  55746. /**
  55747. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55748. */
  55749. this.spriteCellChangeSpeed = 0;
  55750. /**
  55751. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55752. */
  55753. this.startSpriteCellID = 0;
  55754. /**
  55755. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55756. */
  55757. this.endSpriteCellID = 0;
  55758. /**
  55759. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55760. */
  55761. this.spriteCellWidth = 0;
  55762. /**
  55763. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55764. */
  55765. this.spriteCellHeight = 0;
  55766. /**
  55767. * An event triggered when the system is disposed.
  55768. */
  55769. this.onDisposeObservable = new BABYLON.Observable();
  55770. this._particles = new Array();
  55771. this._stockParticles = new Array();
  55772. this._newPartsExcess = 0;
  55773. this._vertexBuffers = {};
  55774. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55775. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55776. this._scaledDirection = BABYLON.Vector3.Zero();
  55777. this._scaledGravity = BABYLON.Vector3.Zero();
  55778. this._currentRenderId = -1;
  55779. this._started = false;
  55780. this._stopped = false;
  55781. this._actualFrame = 0;
  55782. this._vertexBufferSize = 11;
  55783. // start of sub system methods
  55784. /**
  55785. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55786. * Its lifetime will start back at 0.
  55787. */
  55788. this.recycleParticle = function (particle) {
  55789. var lastParticle = _this._particles.pop();
  55790. if (lastParticle !== particle) {
  55791. lastParticle.copyTo(particle);
  55792. }
  55793. _this._stockParticles.push(lastParticle);
  55794. };
  55795. this._createParticle = function () {
  55796. var particle;
  55797. if (_this._stockParticles.length !== 0) {
  55798. particle = _this._stockParticles.pop();
  55799. particle.age = 0;
  55800. particle.cellIndex = _this.startSpriteCellID;
  55801. }
  55802. else {
  55803. particle = new BABYLON.Particle(_this);
  55804. }
  55805. return particle;
  55806. };
  55807. this._emitFromParticle = function (particle) {
  55808. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55809. return;
  55810. }
  55811. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55812. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55813. subSystem._rootParticleSystem = _this;
  55814. _this.activeSubSystems.push(subSystem);
  55815. subSystem.start();
  55816. };
  55817. this._appendParticleVertexes = null;
  55818. this.id = name;
  55819. this.name = name;
  55820. this._capacity = capacity;
  55821. this._epsilon = epsilon;
  55822. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55823. if (isAnimationSheetEnabled) {
  55824. this._vertexBufferSize = 12;
  55825. }
  55826. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55827. this._customEffect = customEffect;
  55828. scene.particleSystems.push(this);
  55829. this._createIndexBuffer();
  55830. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55831. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55832. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55833. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55834. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55835. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55836. if (this._isAnimationSheetEnabled) {
  55837. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55838. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55839. }
  55840. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55841. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55842. this._vertexBuffers["options"] = options;
  55843. // Default emitter type
  55844. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55845. this.updateFunction = function (particles) {
  55846. for (var index = 0; index < particles.length; index++) {
  55847. var particle = particles[index];
  55848. particle.age += _this._scaledUpdateSpeed;
  55849. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55850. _this._emitFromParticle(particle);
  55851. _this.recycleParticle(particle);
  55852. index--;
  55853. continue;
  55854. }
  55855. else {
  55856. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55857. particle.color.addInPlace(_this._scaledColorStep);
  55858. if (particle.color.a < 0)
  55859. particle.color.a = 0;
  55860. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55861. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55862. particle.position.addInPlace(_this._scaledDirection);
  55863. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55864. particle.direction.addInPlace(_this._scaledGravity);
  55865. if (_this._isAnimationSheetEnabled) {
  55866. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55867. }
  55868. }
  55869. }
  55870. };
  55871. }
  55872. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55873. /**
  55874. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55876. */
  55877. get: function () {
  55878. if (this.particleEmitterType.direction1) {
  55879. return this.particleEmitterType.direction1;
  55880. }
  55881. return BABYLON.Vector3.Zero();
  55882. },
  55883. set: function (value) {
  55884. if (this.particleEmitterType.direction1) {
  55885. this.particleEmitterType.direction1 = value;
  55886. }
  55887. },
  55888. enumerable: true,
  55889. configurable: true
  55890. });
  55891. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55892. /**
  55893. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55894. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55895. */
  55896. get: function () {
  55897. if (this.particleEmitterType.direction2) {
  55898. return this.particleEmitterType.direction2;
  55899. }
  55900. return BABYLON.Vector3.Zero();
  55901. },
  55902. set: function (value) {
  55903. if (this.particleEmitterType.direction2) {
  55904. this.particleEmitterType.direction2 = value;
  55905. }
  55906. },
  55907. enumerable: true,
  55908. configurable: true
  55909. });
  55910. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55911. /**
  55912. * 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.
  55913. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55914. */
  55915. get: function () {
  55916. if (this.particleEmitterType.minEmitBox) {
  55917. return this.particleEmitterType.minEmitBox;
  55918. }
  55919. return BABYLON.Vector3.Zero();
  55920. },
  55921. set: function (value) {
  55922. if (this.particleEmitterType.minEmitBox) {
  55923. this.particleEmitterType.minEmitBox = value;
  55924. }
  55925. },
  55926. enumerable: true,
  55927. configurable: true
  55928. });
  55929. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55930. /**
  55931. * 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.
  55932. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55933. */
  55934. get: function () {
  55935. if (this.particleEmitterType.maxEmitBox) {
  55936. return this.particleEmitterType.maxEmitBox;
  55937. }
  55938. return BABYLON.Vector3.Zero();
  55939. },
  55940. set: function (value) {
  55941. if (this.particleEmitterType.maxEmitBox) {
  55942. this.particleEmitterType.maxEmitBox = value;
  55943. }
  55944. },
  55945. enumerable: true,
  55946. configurable: true
  55947. });
  55948. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55949. /**
  55950. * Sets a callback that will be triggered when the system is disposed.
  55951. */
  55952. set: function (callback) {
  55953. if (this._onDisposeObserver) {
  55954. this.onDisposeObservable.remove(this._onDisposeObserver);
  55955. }
  55956. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55957. },
  55958. enumerable: true,
  55959. configurable: true
  55960. });
  55961. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55962. /**
  55963. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55964. */
  55965. get: function () {
  55966. return this._isAnimationSheetEnabled;
  55967. },
  55968. enumerable: true,
  55969. configurable: true
  55970. });
  55971. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55972. //end of Sub-emitter
  55973. /**
  55974. * Gets the current list of active particles
  55975. */
  55976. get: function () {
  55977. return this._particles;
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. /**
  55983. * Returns the string "ParticleSystem"
  55984. * @returns a string containing the class name
  55985. */
  55986. ParticleSystem.prototype.getClassName = function () {
  55987. return "ParticleSystem";
  55988. };
  55989. ParticleSystem.prototype._createIndexBuffer = function () {
  55990. var indices = [];
  55991. var index = 0;
  55992. for (var count = 0; count < this._capacity; count++) {
  55993. indices.push(index);
  55994. indices.push(index + 1);
  55995. indices.push(index + 2);
  55996. indices.push(index);
  55997. indices.push(index + 2);
  55998. indices.push(index + 3);
  55999. index += 4;
  56000. }
  56001. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56002. };
  56003. /**
  56004. * Gets the maximum number of particles active at the same time.
  56005. * @returns The max number of active particles.
  56006. */
  56007. ParticleSystem.prototype.getCapacity = function () {
  56008. return this._capacity;
  56009. };
  56010. /**
  56011. * Gets Wether there are still active particles in the system.
  56012. * @returns True if it is alive, otherwise false.
  56013. */
  56014. ParticleSystem.prototype.isAlive = function () {
  56015. return this._alive;
  56016. };
  56017. /**
  56018. * Gets Wether the system has been started.
  56019. * @returns True if it has been started, otherwise false.
  56020. */
  56021. ParticleSystem.prototype.isStarted = function () {
  56022. return this._started;
  56023. };
  56024. /**
  56025. * Starts the particle system and begins to emit.
  56026. */
  56027. ParticleSystem.prototype.start = function () {
  56028. this._started = true;
  56029. this._stopped = false;
  56030. this._actualFrame = 0;
  56031. if (this.subEmitters && this.subEmitters.length != 0) {
  56032. this.activeSubSystems = new Array();
  56033. }
  56034. };
  56035. /**
  56036. * Stops the particle system.
  56037. * @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.
  56038. */
  56039. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56040. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56041. this._stopped = true;
  56042. if (stopSubEmitters) {
  56043. this._stopSubEmitters();
  56044. }
  56045. };
  56046. // animation sheet
  56047. /**
  56048. * Remove all active particles
  56049. */
  56050. ParticleSystem.prototype.reset = function () {
  56051. this._stockParticles = [];
  56052. this._particles = [];
  56053. };
  56054. /**
  56055. * @hidden (for internal use only)
  56056. */
  56057. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56058. var offset = index * this._vertexBufferSize;
  56059. this._vertexData[offset] = particle.position.x;
  56060. this._vertexData[offset + 1] = particle.position.y;
  56061. this._vertexData[offset + 2] = particle.position.z;
  56062. this._vertexData[offset + 3] = particle.color.r;
  56063. this._vertexData[offset + 4] = particle.color.g;
  56064. this._vertexData[offset + 5] = particle.color.b;
  56065. this._vertexData[offset + 6] = particle.color.a;
  56066. this._vertexData[offset + 7] = particle.angle;
  56067. this._vertexData[offset + 8] = particle.size;
  56068. this._vertexData[offset + 9] = offsetX;
  56069. this._vertexData[offset + 10] = offsetY;
  56070. };
  56071. /**
  56072. * @hidden (for internal use only)
  56073. */
  56074. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56075. if (offsetX === 0)
  56076. offsetX = this._epsilon;
  56077. else if (offsetX === 1)
  56078. offsetX = 1 - this._epsilon;
  56079. if (offsetY === 0)
  56080. offsetY = this._epsilon;
  56081. else if (offsetY === 1)
  56082. offsetY = 1 - this._epsilon;
  56083. var offset = index * this._vertexBufferSize;
  56084. this._vertexData[offset] = particle.position.x;
  56085. this._vertexData[offset + 1] = particle.position.y;
  56086. this._vertexData[offset + 2] = particle.position.z;
  56087. this._vertexData[offset + 3] = particle.color.r;
  56088. this._vertexData[offset + 4] = particle.color.g;
  56089. this._vertexData[offset + 5] = particle.color.b;
  56090. this._vertexData[offset + 6] = particle.color.a;
  56091. this._vertexData[offset + 7] = particle.angle;
  56092. this._vertexData[offset + 8] = particle.size;
  56093. this._vertexData[offset + 9] = offsetX;
  56094. this._vertexData[offset + 10] = offsetY;
  56095. this._vertexData[offset + 11] = particle.cellIndex;
  56096. };
  56097. ParticleSystem.prototype._stopSubEmitters = function () {
  56098. if (!this.activeSubSystems) {
  56099. return;
  56100. }
  56101. this.activeSubSystems.forEach(function (subSystem) {
  56102. subSystem.stop(true);
  56103. });
  56104. this.activeSubSystems = new Array();
  56105. };
  56106. ParticleSystem.prototype._removeFromRoot = function () {
  56107. if (!this._rootParticleSystem) {
  56108. return;
  56109. }
  56110. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56111. if (index !== -1) {
  56112. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56113. }
  56114. };
  56115. // end of sub system methods
  56116. ParticleSystem.prototype._update = function (newParticles) {
  56117. // Update current
  56118. this._alive = this._particles.length > 0;
  56119. this.updateFunction(this._particles);
  56120. // Add new ones
  56121. var worldMatrix;
  56122. if (this.emitter.position) {
  56123. var emitterMesh = this.emitter;
  56124. worldMatrix = emitterMesh.getWorldMatrix();
  56125. }
  56126. else {
  56127. var emitterPosition = this.emitter;
  56128. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56129. }
  56130. var particle;
  56131. for (var index = 0; index < newParticles; index++) {
  56132. if (this._particles.length === this._capacity) {
  56133. break;
  56134. }
  56135. particle = this._createParticle();
  56136. this._particles.push(particle);
  56137. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56138. if (this.startPositionFunction) {
  56139. this.startPositionFunction(worldMatrix, particle.position, particle);
  56140. }
  56141. else {
  56142. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56143. }
  56144. if (this.startDirectionFunction) {
  56145. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56146. }
  56147. else {
  56148. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56149. }
  56150. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56151. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56152. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56153. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56154. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56155. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56156. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56157. }
  56158. };
  56159. ParticleSystem.prototype._getEffect = function () {
  56160. if (this._customEffect) {
  56161. return this._customEffect;
  56162. }
  56163. ;
  56164. var defines = [];
  56165. if (this._scene.clipPlane) {
  56166. defines.push("#define CLIPPLANE");
  56167. }
  56168. if (this._isAnimationSheetEnabled) {
  56169. defines.push("#define ANIMATESHEET");
  56170. }
  56171. // Effect
  56172. var join = defines.join("\n");
  56173. if (this._cachedDefines !== join) {
  56174. this._cachedDefines = join;
  56175. var attributesNamesOrOptions;
  56176. var effectCreationOption;
  56177. if (this._isAnimationSheetEnabled) {
  56178. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56179. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56180. }
  56181. else {
  56182. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56183. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56184. }
  56185. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56186. }
  56187. return this._effect;
  56188. };
  56189. /**
  56190. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56191. */
  56192. ParticleSystem.prototype.animate = function () {
  56193. if (!this._started)
  56194. return;
  56195. var effect = this._getEffect();
  56196. // Check
  56197. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56198. return;
  56199. if (this._currentRenderId === this._scene.getRenderId()) {
  56200. return;
  56201. }
  56202. this._currentRenderId = this._scene.getRenderId();
  56203. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56204. // determine the number of particles we need to create
  56205. var newParticles;
  56206. if (this.manualEmitCount > -1) {
  56207. newParticles = this.manualEmitCount;
  56208. this._newPartsExcess = 0;
  56209. this.manualEmitCount = 0;
  56210. }
  56211. else {
  56212. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56213. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56214. }
  56215. if (this._newPartsExcess > 1.0) {
  56216. newParticles += this._newPartsExcess >> 0;
  56217. this._newPartsExcess -= this._newPartsExcess >> 0;
  56218. }
  56219. this._alive = false;
  56220. if (!this._stopped) {
  56221. this._actualFrame += this._scaledUpdateSpeed;
  56222. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56223. this.stop();
  56224. }
  56225. else {
  56226. newParticles = 0;
  56227. }
  56228. this._update(newParticles);
  56229. // Stopped?
  56230. if (this._stopped) {
  56231. if (!this._alive) {
  56232. this._started = false;
  56233. if (this.onAnimationEnd) {
  56234. this.onAnimationEnd();
  56235. }
  56236. if (this.disposeOnStop) {
  56237. this._scene._toBeDisposed.push(this);
  56238. }
  56239. }
  56240. }
  56241. // Animation sheet
  56242. if (this._isAnimationSheetEnabled) {
  56243. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56244. }
  56245. else {
  56246. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56247. }
  56248. // Update VBO
  56249. var offset = 0;
  56250. for (var index = 0; index < this._particles.length; index++) {
  56251. var particle = this._particles[index];
  56252. this._appendParticleVertexes(offset, particle);
  56253. offset += 4;
  56254. }
  56255. if (this._vertexBuffer) {
  56256. this._vertexBuffer.update(this._vertexData);
  56257. }
  56258. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56259. this.stop();
  56260. }
  56261. };
  56262. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56263. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56264. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56265. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56266. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56267. };
  56268. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56269. this._appendParticleVertex(offset++, particle, 0, 0);
  56270. this._appendParticleVertex(offset++, particle, 1, 0);
  56271. this._appendParticleVertex(offset++, particle, 1, 1);
  56272. this._appendParticleVertex(offset++, particle, 0, 1);
  56273. };
  56274. /**
  56275. * Rebuilds the particle system.
  56276. */
  56277. ParticleSystem.prototype.rebuild = function () {
  56278. this._createIndexBuffer();
  56279. if (this._vertexBuffer) {
  56280. this._vertexBuffer._rebuild();
  56281. }
  56282. };
  56283. /**
  56284. * Is this system ready to be used/rendered
  56285. * @return true if the system is ready
  56286. */
  56287. ParticleSystem.prototype.isReady = function () {
  56288. var effect = this._getEffect();
  56289. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56290. return false;
  56291. }
  56292. return true;
  56293. };
  56294. /**
  56295. * Renders the particle system in its current state.
  56296. * @returns the current number of particles
  56297. */
  56298. ParticleSystem.prototype.render = function () {
  56299. var effect = this._getEffect();
  56300. // Check
  56301. if (!this.isReady() || !this._particles.length) {
  56302. return 0;
  56303. }
  56304. var engine = this._scene.getEngine();
  56305. // Render
  56306. engine.enableEffect(effect);
  56307. engine.setState(false);
  56308. var viewMatrix = this._scene.getViewMatrix();
  56309. effect.setTexture("diffuseSampler", this.particleTexture);
  56310. effect.setMatrix("view", viewMatrix);
  56311. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56312. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56313. var baseSize = this.particleTexture.getBaseSize();
  56314. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56315. }
  56316. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56317. if (this._scene.clipPlane) {
  56318. var clipPlane = this._scene.clipPlane;
  56319. var invView = viewMatrix.clone();
  56320. invView.invert();
  56321. effect.setMatrix("invView", invView);
  56322. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56323. }
  56324. // VBOs
  56325. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56326. // Draw order
  56327. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56328. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56329. }
  56330. else {
  56331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56332. }
  56333. if (this.forceDepthWrite) {
  56334. engine.setDepthWrite(true);
  56335. }
  56336. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56337. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56338. return this._particles.length;
  56339. };
  56340. /**
  56341. * Disposes the particle system and free the associated resources
  56342. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56343. */
  56344. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56345. if (disposeTexture === void 0) { disposeTexture = true; }
  56346. if (this._vertexBuffer) {
  56347. this._vertexBuffer.dispose();
  56348. this._vertexBuffer = null;
  56349. }
  56350. if (this._indexBuffer) {
  56351. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56352. this._indexBuffer = null;
  56353. }
  56354. if (disposeTexture && this.particleTexture) {
  56355. this.particleTexture.dispose();
  56356. this.particleTexture = null;
  56357. }
  56358. this._removeFromRoot();
  56359. // Remove from scene
  56360. var index = this._scene.particleSystems.indexOf(this);
  56361. if (index > -1) {
  56362. this._scene.particleSystems.splice(index, 1);
  56363. }
  56364. // Callback
  56365. this.onDisposeObservable.notifyObservers(this);
  56366. this.onDisposeObservable.clear();
  56367. };
  56368. /**
  56369. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56370. * @param radius The radius of the sphere to emit from
  56371. * @returns the emitter
  56372. */
  56373. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56374. if (radius === void 0) { radius = 1; }
  56375. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56376. this.particleEmitterType = particleEmitter;
  56377. return particleEmitter;
  56378. };
  56379. /**
  56380. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56381. * @param radius The radius of the sphere to emit from
  56382. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56383. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56384. * @returns the emitter
  56385. */
  56386. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56387. if (radius === void 0) { radius = 1; }
  56388. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56389. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56390. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56391. this.particleEmitterType = particleEmitter;
  56392. return particleEmitter;
  56393. };
  56394. /**
  56395. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56396. * @param radius The radius of the cone to emit from
  56397. * @param angle The base angle of the cone
  56398. * @returns the emitter
  56399. */
  56400. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56401. if (radius === void 0) { radius = 1; }
  56402. if (angle === void 0) { angle = Math.PI / 4; }
  56403. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56404. this.particleEmitterType = particleEmitter;
  56405. return particleEmitter;
  56406. };
  56407. // 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.
  56408. /**
  56409. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56410. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56411. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56412. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56413. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56414. * @returns the emitter
  56415. */
  56416. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56417. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56418. this.particleEmitterType = particleEmitter;
  56419. this.direction1 = direction1;
  56420. this.direction2 = direction2;
  56421. this.minEmitBox = minEmitBox;
  56422. this.maxEmitBox = maxEmitBox;
  56423. return particleEmitter;
  56424. };
  56425. // Clone
  56426. /**
  56427. * Clones the particle system.
  56428. * @param name The name of the cloned object
  56429. * @param newEmitter The new emitter to use
  56430. * @returns the cloned particle system
  56431. */
  56432. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56433. var custom = null;
  56434. var program = null;
  56435. if (this.customShader != null) {
  56436. program = this.customShader;
  56437. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56438. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56439. }
  56440. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56441. result.customShader = program;
  56442. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56443. if (newEmitter === undefined) {
  56444. newEmitter = this.emitter;
  56445. }
  56446. result.emitter = newEmitter;
  56447. if (this.particleTexture) {
  56448. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56449. }
  56450. if (!this.preventAutoStart) {
  56451. result.start();
  56452. }
  56453. return result;
  56454. };
  56455. /**
  56456. * Serializes the particle system to a JSON object.
  56457. * @returns the JSON object
  56458. */
  56459. ParticleSystem.prototype.serialize = function () {
  56460. var serializationObject = {};
  56461. serializationObject.name = this.name;
  56462. serializationObject.id = this.id;
  56463. // Emitter
  56464. if (this.emitter.position) {
  56465. var emitterMesh = this.emitter;
  56466. serializationObject.emitterId = emitterMesh.id;
  56467. }
  56468. else {
  56469. var emitterPosition = this.emitter;
  56470. serializationObject.emitter = emitterPosition.asArray();
  56471. }
  56472. serializationObject.capacity = this.getCapacity();
  56473. if (this.particleTexture) {
  56474. serializationObject.textureName = this.particleTexture.name;
  56475. }
  56476. // Animations
  56477. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56478. // Particle system
  56479. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56480. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56481. serializationObject.minSize = this.minSize;
  56482. serializationObject.maxSize = this.maxSize;
  56483. serializationObject.minEmitPower = this.minEmitPower;
  56484. serializationObject.maxEmitPower = this.maxEmitPower;
  56485. serializationObject.minLifeTime = this.minLifeTime;
  56486. serializationObject.maxLifeTime = this.maxLifeTime;
  56487. serializationObject.emitRate = this.emitRate;
  56488. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56489. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56490. serializationObject.gravity = this.gravity.asArray();
  56491. serializationObject.direction1 = this.direction1.asArray();
  56492. serializationObject.direction2 = this.direction2.asArray();
  56493. serializationObject.color1 = this.color1.asArray();
  56494. serializationObject.color2 = this.color2.asArray();
  56495. serializationObject.colorDead = this.colorDead.asArray();
  56496. serializationObject.updateSpeed = this.updateSpeed;
  56497. serializationObject.targetStopDuration = this.targetStopDuration;
  56498. serializationObject.textureMask = this.textureMask.asArray();
  56499. serializationObject.blendMode = this.blendMode;
  56500. serializationObject.customShader = this.customShader;
  56501. serializationObject.preventAutoStart = this.preventAutoStart;
  56502. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56503. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56504. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56505. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56506. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56507. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56508. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56509. // Emitter
  56510. if (this.particleEmitterType) {
  56511. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56512. }
  56513. return serializationObject;
  56514. };
  56515. /**
  56516. * Parses a JSON object to create a particle system.
  56517. * @param parsedParticleSystem The JSON object to parse
  56518. * @param scene The scene to create the particle system in
  56519. * @param rootUrl The root url to use to load external dependencies like texture
  56520. * @returns the Parsed particle system
  56521. */
  56522. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56523. var name = parsedParticleSystem.name;
  56524. var custom = null;
  56525. var program = null;
  56526. if (parsedParticleSystem.customShader) {
  56527. program = parsedParticleSystem.customShader;
  56528. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56529. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56530. }
  56531. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56532. particleSystem.customShader = program;
  56533. if (parsedParticleSystem.id) {
  56534. particleSystem.id = parsedParticleSystem.id;
  56535. }
  56536. // Auto start
  56537. if (parsedParticleSystem.preventAutoStart) {
  56538. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56539. }
  56540. // Texture
  56541. if (parsedParticleSystem.textureName) {
  56542. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56543. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56544. }
  56545. // Emitter
  56546. if (parsedParticleSystem.emitterId) {
  56547. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56548. }
  56549. else {
  56550. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56551. }
  56552. // Animations
  56553. if (parsedParticleSystem.animations) {
  56554. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56555. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56556. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56557. }
  56558. }
  56559. if (parsedParticleSystem.autoAnimate) {
  56560. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56561. }
  56562. // Particle system
  56563. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56564. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56565. particleSystem.minSize = parsedParticleSystem.minSize;
  56566. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56567. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56568. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56569. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56570. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56571. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56572. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56573. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56574. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56575. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56576. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56577. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56578. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56579. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56580. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56581. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56582. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56583. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56584. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56585. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56586. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56587. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56588. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56589. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56590. if (!particleSystem.preventAutoStart) {
  56591. particleSystem.start();
  56592. }
  56593. return particleSystem;
  56594. };
  56595. /**
  56596. * Source color is added to the destination color without alpha affecting the result.
  56597. */
  56598. ParticleSystem.BLENDMODE_ONEONE = 0;
  56599. /**
  56600. * Blend current color and particle color using particle’s alpha.
  56601. */
  56602. ParticleSystem.BLENDMODE_STANDARD = 1;
  56603. return ParticleSystem;
  56604. }());
  56605. BABYLON.ParticleSystem = ParticleSystem;
  56606. })(BABYLON || (BABYLON = {}));
  56607. //# sourceMappingURL=babylon.particleSystem.js.map
  56608. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56609. var BABYLON;
  56610. (function (BABYLON) {
  56611. /**
  56612. * Particle emitter emitting particles from the inside of a box.
  56613. * It emits the particles randomly between 2 given directions.
  56614. */
  56615. var BoxParticleEmitter = /** @class */ (function () {
  56616. /**
  56617. * Creates a new instance BoxParticleEmitter
  56618. */
  56619. function BoxParticleEmitter() {
  56620. /**
  56621. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56622. */
  56623. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56624. /**
  56625. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56626. */
  56627. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56628. /**
  56629. * 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.
  56630. */
  56631. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56632. /**
  56633. * 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.
  56634. */
  56635. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56636. }
  56637. /**
  56638. * Called by the particle System when the direction is computed for the created particle.
  56639. * @param emitPower is the power of the particle (speed)
  56640. * @param worldMatrix is the world matrix of the particle system
  56641. * @param directionToUpdate is the direction vector to update with the result
  56642. * @param particle is the particle we are computed the direction for
  56643. */
  56644. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56645. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56646. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56647. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56648. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56649. };
  56650. /**
  56651. * Called by the particle System when the position is computed for the created particle.
  56652. * @param worldMatrix is the world matrix of the particle system
  56653. * @param positionToUpdate is the position vector to update with the result
  56654. * @param particle is the particle we are computed the position for
  56655. */
  56656. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56657. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56658. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56659. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56660. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56661. };
  56662. /**
  56663. * Clones the current emitter and returns a copy of it
  56664. * @returns the new emitter
  56665. */
  56666. BoxParticleEmitter.prototype.clone = function () {
  56667. var newOne = new BoxParticleEmitter();
  56668. BABYLON.Tools.DeepCopy(this, newOne);
  56669. return newOne;
  56670. };
  56671. /**
  56672. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56673. * @param effect defines the update shader
  56674. */
  56675. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56676. effect.setVector3("direction1", this.direction1);
  56677. effect.setVector3("direction2", this.direction2);
  56678. effect.setVector3("minEmitBox", this.minEmitBox);
  56679. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56680. };
  56681. /**
  56682. * Returns a string to use to update the GPU particles update shader
  56683. * @returns a string containng the defines string
  56684. */
  56685. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56686. return "#define BOXEMITTER";
  56687. };
  56688. /**
  56689. * Returns the string "BoxEmitter"
  56690. * @returns a string containing the class name
  56691. */
  56692. BoxParticleEmitter.prototype.getClassName = function () {
  56693. return "BoxEmitter";
  56694. };
  56695. /**
  56696. * Serializes the particle system to a JSON object.
  56697. * @returns the JSON object
  56698. */
  56699. BoxParticleEmitter.prototype.serialize = function () {
  56700. var serializationObject = {};
  56701. serializationObject.type = this.getClassName();
  56702. serializationObject.direction1 = this.direction1.asArray();
  56703. serializationObject.direction2 = this.direction2.asArray();
  56704. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56705. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56706. return serializationObject;
  56707. };
  56708. /**
  56709. * Parse properties from a JSON object
  56710. * @param serializationObject defines the JSON object
  56711. */
  56712. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56713. this.direction1.copyFrom(serializationObject.direction1);
  56714. this.direction2.copyFrom(serializationObject.direction2);
  56715. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56716. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56717. };
  56718. return BoxParticleEmitter;
  56719. }());
  56720. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56721. })(BABYLON || (BABYLON = {}));
  56722. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56723. var BABYLON;
  56724. (function (BABYLON) {
  56725. /**
  56726. * Particle emitter emitting particles from the inside of a cone.
  56727. * It emits the particles alongside the cone volume from the base to the particle.
  56728. * The emission direction might be randomized.
  56729. */
  56730. var ConeParticleEmitter = /** @class */ (function () {
  56731. /**
  56732. * Creates a new instance ConeParticleEmitter
  56733. * @param radius the radius of the emission cone (1 by default)
  56734. * @param angles the cone base angle (PI by default)
  56735. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56736. */
  56737. function ConeParticleEmitter(radius,
  56738. /**
  56739. * The radius of the emission cone.
  56740. */
  56741. angle,
  56742. /**
  56743. * The cone base angle.
  56744. */
  56745. directionRandomizer) {
  56746. if (radius === void 0) { radius = 1; }
  56747. if (angle === void 0) { angle = Math.PI; }
  56748. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56749. this.angle = angle;
  56750. this.directionRandomizer = directionRandomizer;
  56751. this.radius = radius;
  56752. }
  56753. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56754. /**
  56755. * Gets the radius of the emission cone.
  56756. */
  56757. get: function () {
  56758. return this._radius;
  56759. },
  56760. /**
  56761. * Sets the radius of the emission cone.
  56762. */
  56763. set: function (value) {
  56764. this._radius = value;
  56765. if (this.angle !== 0) {
  56766. this._height = value / Math.tan(this.angle / 2);
  56767. }
  56768. else {
  56769. this._height = 1;
  56770. }
  56771. },
  56772. enumerable: true,
  56773. configurable: true
  56774. });
  56775. /**
  56776. * Called by the particle System when the direction is computed for the created particle.
  56777. * @param emitPower is the power of the particle (speed)
  56778. * @param worldMatrix is the world matrix of the particle system
  56779. * @param directionToUpdate is the direction vector to update with the result
  56780. * @param particle is the particle we are computed the direction for
  56781. */
  56782. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56783. if (this.angle === 0) {
  56784. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56785. }
  56786. else {
  56787. // measure the direction Vector from the emitter to the particle.
  56788. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56789. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56790. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56791. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56792. direction.x += randX;
  56793. direction.y += randY;
  56794. direction.z += randZ;
  56795. direction.normalize();
  56796. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56797. }
  56798. };
  56799. /**
  56800. * Called by the particle System when the position is computed for the created particle.
  56801. * @param worldMatrix is the world matrix of the particle system
  56802. * @param positionToUpdate is the position vector to update with the result
  56803. * @param particle is the particle we are computed the position for
  56804. */
  56805. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56806. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56807. var h = BABYLON.Scalar.RandomRange(0, 1);
  56808. // Better distribution in a cone at normal angles.
  56809. h = 1 - h * h;
  56810. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56811. radius = radius * h;
  56812. var randX = radius * Math.sin(s);
  56813. var randZ = radius * Math.cos(s);
  56814. var randY = h * this._height;
  56815. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56816. };
  56817. /**
  56818. * Clones the current emitter and returns a copy of it
  56819. * @returns the new emitter
  56820. */
  56821. ConeParticleEmitter.prototype.clone = function () {
  56822. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56823. BABYLON.Tools.DeepCopy(this, newOne);
  56824. return newOne;
  56825. };
  56826. /**
  56827. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56828. * @param effect defines the update shader
  56829. */
  56830. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56831. effect.setFloat("radius", this.radius);
  56832. effect.setFloat("angle", this.angle);
  56833. effect.setFloat("height", this._height);
  56834. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56835. };
  56836. /**
  56837. * Returns a string to use to update the GPU particles update shader
  56838. * @returns a string containng the defines string
  56839. */
  56840. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56841. return "#define CONEEMITTER";
  56842. };
  56843. /**
  56844. * Returns the string "BoxEmitter"
  56845. * @returns a string containing the class name
  56846. */
  56847. ConeParticleEmitter.prototype.getClassName = function () {
  56848. return "ConeEmitter";
  56849. };
  56850. /**
  56851. * Serializes the particle system to a JSON object.
  56852. * @returns the JSON object
  56853. */
  56854. ConeParticleEmitter.prototype.serialize = function () {
  56855. var serializationObject = {};
  56856. serializationObject.type = this.getClassName();
  56857. serializationObject.radius = this.radius;
  56858. serializationObject.angle = this.angle;
  56859. serializationObject.directionRandomizer = this.directionRandomizer;
  56860. return serializationObject;
  56861. };
  56862. /**
  56863. * Parse properties from a JSON object
  56864. * @param serializationObject defines the JSON object
  56865. */
  56866. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56867. this.radius = serializationObject.radius;
  56868. this.angle = serializationObject.angle;
  56869. this.directionRandomizer = serializationObject.directionRandomizer;
  56870. };
  56871. return ConeParticleEmitter;
  56872. }());
  56873. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56874. })(BABYLON || (BABYLON = {}));
  56875. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56876. var BABYLON;
  56877. (function (BABYLON) {
  56878. /**
  56879. * Particle emitter emitting particles from the inside of a sphere.
  56880. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56881. */
  56882. var SphereParticleEmitter = /** @class */ (function () {
  56883. /**
  56884. * Creates a new instance SphereParticleEmitter
  56885. * @param radius the radius of the emission sphere (1 by default)
  56886. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56887. */
  56888. function SphereParticleEmitter(
  56889. /**
  56890. * The radius of the emission sphere.
  56891. */
  56892. radius,
  56893. /**
  56894. * How much to randomize the particle direction [0-1].
  56895. */
  56896. directionRandomizer) {
  56897. if (radius === void 0) { radius = 1; }
  56898. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56899. this.radius = radius;
  56900. this.directionRandomizer = directionRandomizer;
  56901. }
  56902. /**
  56903. * Called by the particle System when the direction is computed for the created particle.
  56904. * @param emitPower is the power of the particle (speed)
  56905. * @param worldMatrix is the world matrix of the particle system
  56906. * @param directionToUpdate is the direction vector to update with the result
  56907. * @param particle is the particle we are computed the direction for
  56908. */
  56909. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56910. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56911. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56912. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56913. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56914. direction.x += randX;
  56915. direction.y += randY;
  56916. direction.z += randZ;
  56917. direction.normalize();
  56918. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56919. };
  56920. /**
  56921. * Called by the particle System when the position is computed for the created particle.
  56922. * @param worldMatrix is the world matrix of the particle system
  56923. * @param positionToUpdate is the position vector to update with the result
  56924. * @param particle is the particle we are computed the position for
  56925. */
  56926. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56927. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56928. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56929. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56930. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56931. var randY = randRadius * Math.cos(theta);
  56932. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56934. };
  56935. /**
  56936. * Clones the current emitter and returns a copy of it
  56937. * @returns the new emitter
  56938. */
  56939. SphereParticleEmitter.prototype.clone = function () {
  56940. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56941. BABYLON.Tools.DeepCopy(this, newOne);
  56942. return newOne;
  56943. };
  56944. /**
  56945. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56946. * @param effect defines the update shader
  56947. */
  56948. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56949. effect.setFloat("radius", this.radius);
  56950. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56951. };
  56952. /**
  56953. * Returns a string to use to update the GPU particles update shader
  56954. * @returns a string containng the defines string
  56955. */
  56956. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56957. return "#define SPHEREEMITTER";
  56958. };
  56959. /**
  56960. * Returns the string "SphereParticleEmitter"
  56961. * @returns a string containing the class name
  56962. */
  56963. SphereParticleEmitter.prototype.getClassName = function () {
  56964. return "SphereParticleEmitter";
  56965. };
  56966. /**
  56967. * Serializes the particle system to a JSON object.
  56968. * @returns the JSON object
  56969. */
  56970. SphereParticleEmitter.prototype.serialize = function () {
  56971. var serializationObject = {};
  56972. serializationObject.type = this.getClassName();
  56973. serializationObject.radius = this.radius;
  56974. serializationObject.directionRandomizer = this.directionRandomizer;
  56975. return serializationObject;
  56976. };
  56977. /**
  56978. * Parse properties from a JSON object
  56979. * @param serializationObject defines the JSON object
  56980. */
  56981. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56982. this.radius = serializationObject.radius;
  56983. this.directionRandomizer = serializationObject.directionRandomizer;
  56984. };
  56985. return SphereParticleEmitter;
  56986. }());
  56987. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56988. /**
  56989. * Particle emitter emitting particles from the inside of a sphere.
  56990. * It emits the particles randomly between two vectors.
  56991. */
  56992. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56993. __extends(SphereDirectedParticleEmitter, _super);
  56994. /**
  56995. * Creates a new instance SphereDirectedParticleEmitter
  56996. * @param radius the radius of the emission sphere (1 by default)
  56997. * @param direction1 the min limit of the emission direction (up vector by default)
  56998. * @param direction2 the max limit of the emission direction (up vector by default)
  56999. */
  57000. function SphereDirectedParticleEmitter(radius,
  57001. /**
  57002. * The min limit of the emission direction.
  57003. */
  57004. direction1,
  57005. /**
  57006. * The max limit of the emission direction.
  57007. */
  57008. direction2) {
  57009. if (radius === void 0) { radius = 1; }
  57010. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57011. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57012. var _this = _super.call(this, radius) || this;
  57013. _this.direction1 = direction1;
  57014. _this.direction2 = direction2;
  57015. return _this;
  57016. }
  57017. /**
  57018. * Called by the particle System when the direction is computed for the created particle.
  57019. * @param emitPower is the power of the particle (speed)
  57020. * @param worldMatrix is the world matrix of the particle system
  57021. * @param directionToUpdate is the direction vector to update with the result
  57022. * @param particle is the particle we are computed the direction for
  57023. */
  57024. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57025. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57026. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57027. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57028. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57029. };
  57030. /**
  57031. * Clones the current emitter and returns a copy of it
  57032. * @returns the new emitter
  57033. */
  57034. SphereDirectedParticleEmitter.prototype.clone = function () {
  57035. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57036. BABYLON.Tools.DeepCopy(this, newOne);
  57037. return newOne;
  57038. };
  57039. /**
  57040. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57041. * @param effect defines the update shader
  57042. */
  57043. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57044. effect.setFloat("radius", this.radius);
  57045. effect.setVector3("direction1", this.direction1);
  57046. effect.setVector3("direction2", this.direction2);
  57047. };
  57048. /**
  57049. * Returns a string to use to update the GPU particles update shader
  57050. * @returns a string containng the defines string
  57051. */
  57052. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57053. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57054. };
  57055. /**
  57056. * Returns the string "SphereDirectedParticleEmitter"
  57057. * @returns a string containing the class name
  57058. */
  57059. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57060. return "SphereDirectedParticleEmitter";
  57061. };
  57062. /**
  57063. * Serializes the particle system to a JSON object.
  57064. * @returns the JSON object
  57065. */
  57066. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57067. var serializationObject = _super.prototype.serialize.call(this);
  57068. serializationObject.direction1 = this.direction1.asArray();
  57069. serializationObject.direction2 = this.direction2.asArray();
  57070. return serializationObject;
  57071. };
  57072. /**
  57073. * Parse properties from a JSON object
  57074. * @param serializationObject defines the JSON object
  57075. */
  57076. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57077. _super.prototype.parse.call(this, serializationObject);
  57078. this.direction1.copyFrom(serializationObject.direction1);
  57079. this.direction2.copyFrom(serializationObject.direction2);
  57080. };
  57081. return SphereDirectedParticleEmitter;
  57082. }(SphereParticleEmitter));
  57083. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57084. })(BABYLON || (BABYLON = {}));
  57085. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57086. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57087. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57088. s = arguments[i];
  57089. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57090. t[p] = s[p];
  57091. }
  57092. return t;
  57093. };
  57094. var BABYLON;
  57095. (function (BABYLON) {
  57096. /**
  57097. * This represents a GPU particle system in Babylon
  57098. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57099. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57100. */
  57101. var GPUParticleSystem = /** @class */ (function () {
  57102. /**
  57103. * Instantiates a GPU particle system.
  57104. * 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.
  57105. * @param name The name of the particle system
  57106. * @param capacity The max number of particles alive at the same time
  57107. * @param scene The scene the particle system belongs to
  57108. */
  57109. function GPUParticleSystem(name, options, scene) {
  57110. /**
  57111. * The emitter represents the Mesh or position we are attaching the particle system to.
  57112. */
  57113. this.emitter = null;
  57114. /**
  57115. * The rendering group used by the Particle system to chose when to render.
  57116. */
  57117. this.renderingGroupId = 0;
  57118. /**
  57119. * The layer mask we are rendering the particles through.
  57120. */
  57121. this.layerMask = 0x0FFFFFFF;
  57122. this._targetIndex = 0;
  57123. this._currentRenderId = -1;
  57124. this._started = false;
  57125. this._stopped = false;
  57126. this._timeDelta = 0;
  57127. this._attributesStrideSize = 14;
  57128. this._actualFrame = 0;
  57129. /**
  57130. * List of animations used by the particle system.
  57131. */
  57132. this.animations = [];
  57133. /**
  57134. * An event triggered when the system is disposed.
  57135. */
  57136. this.onDisposeObservable = new BABYLON.Observable();
  57137. /**
  57138. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57139. */
  57140. this.updateSpeed = 0.01;
  57141. /**
  57142. * The amount of time the particle system is running (depends of the overall update speed).
  57143. */
  57144. this.targetStopDuration = 0;
  57145. /**
  57146. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57147. */
  57148. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57149. /**
  57150. * Minimum life time of emitting particles.
  57151. */
  57152. this.minLifeTime = 1;
  57153. /**
  57154. * Maximum life time of emitting particles.
  57155. */
  57156. this.maxLifeTime = 1;
  57157. /**
  57158. * Minimum Size of emitting particles.
  57159. */
  57160. this.minSize = 1;
  57161. /**
  57162. * Maximum Size of emitting particles.
  57163. */
  57164. this.maxSize = 1;
  57165. /**
  57166. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57167. */
  57168. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57169. /**
  57170. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57171. */
  57172. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57173. /**
  57174. * Color the particle will have at the end of its lifetime.
  57175. */
  57176. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57177. /**
  57178. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57179. */
  57180. this.emitRate = 100;
  57181. /**
  57182. * You can use gravity if you want to give an orientation to your particles.
  57183. */
  57184. this.gravity = BABYLON.Vector3.Zero();
  57185. /**
  57186. * Minimum power of emitting particles.
  57187. */
  57188. this.minEmitPower = 1;
  57189. /**
  57190. * Maximum power of emitting particles.
  57191. */
  57192. this.maxEmitPower = 1;
  57193. /**
  57194. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57195. * to override the particles.
  57196. */
  57197. this.forceDepthWrite = false;
  57198. this.id = name;
  57199. this.name = name;
  57200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57201. this._engine = this._scene.getEngine();
  57202. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57203. this._capacity = fullOptions.capacity;
  57204. this._activeCount = fullOptions.capacity;
  57205. this._currentActiveCount = 0;
  57206. this._scene.particleSystems.push(this);
  57207. this._updateEffectOptions = {
  57208. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57209. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57210. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57211. uniformBuffersNames: [],
  57212. samplers: ["randomSampler"],
  57213. defines: "",
  57214. fallbacks: null,
  57215. onCompiled: null,
  57216. onError: null,
  57217. indexParameters: null,
  57218. maxSimultaneousLights: 0,
  57219. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57220. };
  57221. // Random data
  57222. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57223. var d = [];
  57224. for (var i = 0; i < maxTextureSize; ++i) {
  57225. d.push(Math.random());
  57226. d.push(Math.random());
  57227. d.push(Math.random());
  57228. d.push(Math.random());
  57229. }
  57230. 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);
  57231. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57232. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57233. this._randomTextureSize = maxTextureSize;
  57234. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57235. }
  57236. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57237. /**
  57238. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57239. */
  57240. get: function () {
  57241. if (!BABYLON.Engine.LastCreatedEngine) {
  57242. return false;
  57243. }
  57244. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57245. },
  57246. enumerable: true,
  57247. configurable: true
  57248. });
  57249. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57250. /**
  57251. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57252. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57253. */
  57254. get: function () {
  57255. if (this.particleEmitterType.direction1) {
  57256. return this.particleEmitterType.direction1;
  57257. }
  57258. return BABYLON.Vector3.Zero();
  57259. },
  57260. set: function (value) {
  57261. if (this.particleEmitterType.direction1) {
  57262. this.particleEmitterType.direction1 = value;
  57263. }
  57264. },
  57265. enumerable: true,
  57266. configurable: true
  57267. });
  57268. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57269. /**
  57270. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57271. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57272. */
  57273. get: function () {
  57274. if (this.particleEmitterType.direction2) {
  57275. return this.particleEmitterType.direction2;
  57276. }
  57277. return BABYLON.Vector3.Zero();
  57278. },
  57279. set: function (value) {
  57280. if (this.particleEmitterType.direction2) {
  57281. this.particleEmitterType.direction2 = value;
  57282. }
  57283. },
  57284. enumerable: true,
  57285. configurable: true
  57286. });
  57287. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57288. /**
  57289. * 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.
  57290. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57291. */
  57292. get: function () {
  57293. if (this.particleEmitterType.minEmitBox) {
  57294. return this.particleEmitterType.minEmitBox;
  57295. }
  57296. return BABYLON.Vector3.Zero();
  57297. },
  57298. set: function (value) {
  57299. if (this.particleEmitterType.minEmitBox) {
  57300. this.particleEmitterType.minEmitBox = value;
  57301. }
  57302. },
  57303. enumerable: true,
  57304. configurable: true
  57305. });
  57306. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57307. /**
  57308. * 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.
  57309. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57310. */
  57311. get: function () {
  57312. if (this.particleEmitterType.maxEmitBox) {
  57313. return this.particleEmitterType.maxEmitBox;
  57314. }
  57315. return BABYLON.Vector3.Zero();
  57316. },
  57317. set: function (value) {
  57318. if (this.particleEmitterType.maxEmitBox) {
  57319. this.particleEmitterType.maxEmitBox = value;
  57320. }
  57321. },
  57322. enumerable: true,
  57323. configurable: true
  57324. });
  57325. /**
  57326. * Gets the maximum number of particles active at the same time.
  57327. * @returns The max number of active particles.
  57328. */
  57329. GPUParticleSystem.prototype.getCapacity = function () {
  57330. return this._capacity;
  57331. };
  57332. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57333. /**
  57334. * Gets or set the number of active particles
  57335. */
  57336. get: function () {
  57337. return this._activeCount;
  57338. },
  57339. set: function (value) {
  57340. this._activeCount = Math.min(value, this._capacity);
  57341. },
  57342. enumerable: true,
  57343. configurable: true
  57344. });
  57345. /**
  57346. * Is this system ready to be used/rendered
  57347. * @return true if the system is ready
  57348. */
  57349. GPUParticleSystem.prototype.isReady = function () {
  57350. if (!this._updateEffect) {
  57351. this._recreateUpdateEffect();
  57352. this._recreateRenderEffect();
  57353. return false;
  57354. }
  57355. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57356. return false;
  57357. }
  57358. return true;
  57359. };
  57360. /**
  57361. * Gets Wether the system has been started.
  57362. * @returns True if it has been started, otherwise false.
  57363. */
  57364. GPUParticleSystem.prototype.isStarted = function () {
  57365. return this._started;
  57366. };
  57367. /**
  57368. * Starts the particle system and begins to emit.
  57369. */
  57370. GPUParticleSystem.prototype.start = function () {
  57371. this._started = true;
  57372. this._stopped = false;
  57373. };
  57374. /**
  57375. * Stops the particle system.
  57376. */
  57377. GPUParticleSystem.prototype.stop = function () {
  57378. this._stopped = true;
  57379. };
  57380. /**
  57381. * Remove all active particles
  57382. */
  57383. GPUParticleSystem.prototype.reset = function () {
  57384. this._releaseBuffers();
  57385. this._releaseVAOs();
  57386. this._currentActiveCount = 0;
  57387. this._targetIndex = 0;
  57388. };
  57389. /**
  57390. * Returns the string "GPUParticleSystem"
  57391. * @returns a string containing the class name
  57392. */
  57393. GPUParticleSystem.prototype.getClassName = function () {
  57394. return "GPUParticleSystem";
  57395. };
  57396. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57397. var updateVertexBuffers = {};
  57398. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57399. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57400. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57401. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57402. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57403. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57404. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57405. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57406. this._engine.bindArrayBuffer(null);
  57407. return vao;
  57408. };
  57409. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57410. var renderVertexBuffers = {};
  57411. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57412. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57413. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57414. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57415. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57416. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57417. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57418. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57419. this._engine.bindArrayBuffer(null);
  57420. return vao;
  57421. };
  57422. GPUParticleSystem.prototype._initialize = function (force) {
  57423. if (force === void 0) { force = false; }
  57424. if (this._buffer0 && !force) {
  57425. return;
  57426. }
  57427. var engine = this._scene.getEngine();
  57428. var data = new Array();
  57429. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57430. // position
  57431. data.push(0.0);
  57432. data.push(0.0);
  57433. data.push(0.0);
  57434. // Age and life
  57435. data.push(0.0); // create the particle as a dead one to create a new one at start
  57436. data.push(0.0);
  57437. // Seed
  57438. data.push(Math.random());
  57439. // Size
  57440. data.push(0.0);
  57441. // color
  57442. data.push(0.0);
  57443. data.push(0.0);
  57444. data.push(0.0);
  57445. data.push(0.0);
  57446. // direction
  57447. data.push(0.0);
  57448. data.push(0.0);
  57449. data.push(0.0);
  57450. }
  57451. // Sprite data
  57452. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57453. -0.5, 0.5, 0, 1,
  57454. -0.5, -0.5, 0, 0,
  57455. 0.5, -0.5, 1, 0]);
  57456. // Buffers
  57457. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57458. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57459. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57460. // Update VAO
  57461. this._updateVAO = [];
  57462. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57463. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57464. // Render VAO
  57465. this._renderVAO = [];
  57466. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57467. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57468. // Links
  57469. this._sourceBuffer = this._buffer0;
  57470. this._targetBuffer = this._buffer1;
  57471. };
  57472. /** @hidden */
  57473. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57474. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57475. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57476. return;
  57477. }
  57478. this._updateEffectOptions.defines = defines;
  57479. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57480. };
  57481. /** @hidden */
  57482. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57483. var defines = "";
  57484. if (this._scene.clipPlane) {
  57485. defines = "\n#define CLIPPLANE";
  57486. }
  57487. if (this._renderEffect && this._renderEffect.defines === defines) {
  57488. return;
  57489. }
  57490. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57491. };
  57492. /**
  57493. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57494. */
  57495. GPUParticleSystem.prototype.animate = function () {
  57496. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57497. this._actualFrame += this._timeDelta;
  57498. if (!this._stopped) {
  57499. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57500. this.stop();
  57501. }
  57502. }
  57503. };
  57504. /**
  57505. * Renders the particle system in its current state.
  57506. * @returns the current number of particles
  57507. */
  57508. GPUParticleSystem.prototype.render = function () {
  57509. if (!this._started) {
  57510. return 0;
  57511. }
  57512. this._recreateUpdateEffect();
  57513. this._recreateRenderEffect();
  57514. if (!this.isReady()) {
  57515. return 0;
  57516. }
  57517. if (this._currentRenderId === this._scene.getRenderId()) {
  57518. return 0;
  57519. }
  57520. this._currentRenderId = this._scene.getRenderId();
  57521. // Get everything ready to render
  57522. this._initialize();
  57523. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57524. // Enable update effect
  57525. this._engine.enableEffect(this._updateEffect);
  57526. this._engine.setState(false);
  57527. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57528. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57529. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57530. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57531. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57532. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57533. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57534. this._updateEffect.setDirectColor4("color1", this.color1);
  57535. this._updateEffect.setDirectColor4("color2", this.color2);
  57536. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57537. this._updateEffect.setVector3("gravity", this.gravity);
  57538. if (this.particleEmitterType) {
  57539. this.particleEmitterType.applyToShader(this._updateEffect);
  57540. }
  57541. var emitterWM;
  57542. if (this.emitter.position) {
  57543. var emitterMesh = this.emitter;
  57544. emitterWM = emitterMesh.getWorldMatrix();
  57545. }
  57546. else {
  57547. var emitterPosition = this.emitter;
  57548. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57549. }
  57550. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57551. // Bind source VAO
  57552. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57553. // Update
  57554. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57555. this._engine.setRasterizerState(false);
  57556. this._engine.beginTransformFeedback();
  57557. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57558. this._engine.endTransformFeedback();
  57559. this._engine.setRasterizerState(true);
  57560. this._engine.bindTransformFeedbackBuffer(null);
  57561. // Enable render effect
  57562. this._engine.enableEffect(this._renderEffect);
  57563. var viewMatrix = this._scene.getViewMatrix();
  57564. this._renderEffect.setMatrix("view", viewMatrix);
  57565. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57566. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57567. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57568. if (this._scene.clipPlane) {
  57569. var clipPlane = this._scene.clipPlane;
  57570. var invView = viewMatrix.clone();
  57571. invView.invert();
  57572. this._renderEffect.setMatrix("invView", invView);
  57573. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57574. }
  57575. // Draw order
  57576. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57577. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57578. }
  57579. else {
  57580. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57581. }
  57582. if (this.forceDepthWrite) {
  57583. this._engine.setDepthWrite(true);
  57584. }
  57585. // Bind source VAO
  57586. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57587. // Render
  57588. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57589. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57590. // Switch VAOs
  57591. this._targetIndex++;
  57592. if (this._targetIndex === 2) {
  57593. this._targetIndex = 0;
  57594. }
  57595. // Switch buffers
  57596. var tmpBuffer = this._sourceBuffer;
  57597. this._sourceBuffer = this._targetBuffer;
  57598. this._targetBuffer = tmpBuffer;
  57599. return this._currentActiveCount;
  57600. };
  57601. /**
  57602. * Rebuilds the particle system
  57603. */
  57604. GPUParticleSystem.prototype.rebuild = function () {
  57605. this._initialize(true);
  57606. };
  57607. GPUParticleSystem.prototype._releaseBuffers = function () {
  57608. if (this._buffer0) {
  57609. this._buffer0.dispose();
  57610. this._buffer0 = null;
  57611. }
  57612. if (this._buffer1) {
  57613. this._buffer1.dispose();
  57614. this._buffer1 = null;
  57615. }
  57616. if (this._spriteBuffer) {
  57617. this._spriteBuffer.dispose();
  57618. this._spriteBuffer = null;
  57619. }
  57620. };
  57621. GPUParticleSystem.prototype._releaseVAOs = function () {
  57622. if (!this._updateVAO) {
  57623. return;
  57624. }
  57625. for (var index = 0; index < this._updateVAO.length; index++) {
  57626. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57627. }
  57628. this._updateVAO = [];
  57629. for (var index = 0; index < this._renderVAO.length; index++) {
  57630. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57631. }
  57632. this._renderVAO = [];
  57633. };
  57634. /**
  57635. * Disposes the particle system and free the associated resources
  57636. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57637. */
  57638. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57639. if (disposeTexture === void 0) { disposeTexture = true; }
  57640. var index = this._scene.particleSystems.indexOf(this);
  57641. if (index > -1) {
  57642. this._scene.particleSystems.splice(index, 1);
  57643. }
  57644. this._releaseBuffers();
  57645. this._releaseVAOs();
  57646. if (this._randomTexture) {
  57647. this._randomTexture.dispose();
  57648. this._randomTexture = null;
  57649. }
  57650. if (disposeTexture && this.particleTexture) {
  57651. this.particleTexture.dispose();
  57652. this.particleTexture = null;
  57653. }
  57654. // Callback
  57655. this.onDisposeObservable.notifyObservers(this);
  57656. this.onDisposeObservable.clear();
  57657. };
  57658. /**
  57659. * Clones the particle system.
  57660. * @param name The name of the cloned object
  57661. * @param newEmitter The new emitter to use
  57662. * @returns the cloned particle system
  57663. */
  57664. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57665. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57666. BABYLON.Tools.DeepCopy(this, result);
  57667. if (newEmitter === undefined) {
  57668. newEmitter = this.emitter;
  57669. }
  57670. result.emitter = newEmitter;
  57671. if (this.particleTexture) {
  57672. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57673. }
  57674. return result;
  57675. };
  57676. /**
  57677. * Serializes the particle system to a JSON object.
  57678. * @returns the JSON object
  57679. */
  57680. GPUParticleSystem.prototype.serialize = function () {
  57681. var serializationObject = {};
  57682. serializationObject.name = this.name;
  57683. serializationObject.id = this.id;
  57684. // Emitter
  57685. if (this.emitter.position) {
  57686. var emitterMesh = this.emitter;
  57687. serializationObject.emitterId = emitterMesh.id;
  57688. }
  57689. else {
  57690. var emitterPosition = this.emitter;
  57691. serializationObject.emitter = emitterPosition.asArray();
  57692. }
  57693. serializationObject.capacity = this.getCapacity();
  57694. if (this.particleTexture) {
  57695. serializationObject.textureName = this.particleTexture.name;
  57696. }
  57697. // Animations
  57698. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57699. // Particle system
  57700. serializationObject.activeParticleCount = this.activeParticleCount;
  57701. serializationObject.randomTextureSize = this._randomTextureSize;
  57702. serializationObject.minSize = this.minSize;
  57703. serializationObject.maxSize = this.maxSize;
  57704. serializationObject.minEmitPower = this.minEmitPower;
  57705. serializationObject.maxEmitPower = this.maxEmitPower;
  57706. serializationObject.minLifeTime = this.minLifeTime;
  57707. serializationObject.maxLifeTime = this.maxLifeTime;
  57708. serializationObject.emitRate = this.emitRate;
  57709. serializationObject.gravity = this.gravity.asArray();
  57710. serializationObject.color1 = this.color1.asArray();
  57711. serializationObject.color2 = this.color2.asArray();
  57712. serializationObject.colorDead = this.colorDead.asArray();
  57713. serializationObject.updateSpeed = this.updateSpeed;
  57714. serializationObject.targetStopDuration = this.targetStopDuration;
  57715. serializationObject.blendMode = this.blendMode;
  57716. // Emitter
  57717. if (this.particleEmitterType) {
  57718. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57719. }
  57720. return serializationObject;
  57721. };
  57722. /**
  57723. * Parses a JSON object to create a GPU particle system.
  57724. * @param parsedParticleSystem The JSON object to parse
  57725. * @param scene The scene to create the particle system in
  57726. * @param rootUrl The root url to use to load external dependencies like texture
  57727. * @returns the parsed GPU particle system
  57728. */
  57729. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57730. var name = parsedParticleSystem.name;
  57731. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57732. if (parsedParticleSystem.id) {
  57733. particleSystem.id = parsedParticleSystem.id;
  57734. }
  57735. // Texture
  57736. if (parsedParticleSystem.textureName) {
  57737. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57738. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57739. }
  57740. // Emitter
  57741. if (parsedParticleSystem.emitterId) {
  57742. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57743. }
  57744. else {
  57745. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57746. }
  57747. // Animations
  57748. if (parsedParticleSystem.animations) {
  57749. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57750. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57751. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57752. }
  57753. }
  57754. // Particle system
  57755. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57756. particleSystem.minSize = parsedParticleSystem.minSize;
  57757. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57758. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57759. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57760. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57761. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57762. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57763. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57764. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57765. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57766. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57767. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57768. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57769. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57770. // Emitter
  57771. if (parsedParticleSystem.particleEmitterType) {
  57772. var emitterType = void 0;
  57773. switch (parsedParticleSystem.particleEmitterType.type) {
  57774. case "SphereEmitter":
  57775. emitterType = new BABYLON.SphereParticleEmitter();
  57776. break;
  57777. case "SphereDirectedParticleEmitter":
  57778. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57779. break;
  57780. case "ConeEmitter":
  57781. emitterType = new BABYLON.ConeParticleEmitter();
  57782. break;
  57783. case "BoxEmitter":
  57784. default:
  57785. emitterType = new BABYLON.BoxParticleEmitter();
  57786. break;
  57787. }
  57788. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57789. particleSystem.particleEmitterType = emitterType;
  57790. }
  57791. return particleSystem;
  57792. };
  57793. return GPUParticleSystem;
  57794. }());
  57795. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57796. })(BABYLON || (BABYLON = {}));
  57797. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57798. var BABYLON;
  57799. (function (BABYLON) {
  57800. /**
  57801. * Represents one particle of a solid particle system.
  57802. */
  57803. var SolidParticle = /** @class */ (function () {
  57804. /**
  57805. * Creates a Solid Particle object.
  57806. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57807. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57808. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57809. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57810. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57811. * @param shapeId (integer) is the model shape identifier in the SPS.
  57812. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57813. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57814. */
  57815. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57816. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57817. /**
  57818. * particle global index
  57819. */
  57820. this.idx = 0;
  57821. /**
  57822. * The color of the particle
  57823. */
  57824. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57825. /**
  57826. * The world space position of the particle.
  57827. */
  57828. this.position = BABYLON.Vector3.Zero();
  57829. /**
  57830. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57831. */
  57832. this.rotation = BABYLON.Vector3.Zero();
  57833. /**
  57834. * The scaling of the particle.
  57835. */
  57836. this.scaling = BABYLON.Vector3.One();
  57837. /**
  57838. * The uvs of the particle.
  57839. */
  57840. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57841. /**
  57842. * The current speed of the particle.
  57843. */
  57844. this.velocity = BABYLON.Vector3.Zero();
  57845. /**
  57846. * The pivot point in the particle local space.
  57847. */
  57848. this.pivot = BABYLON.Vector3.Zero();
  57849. /**
  57850. * Must the particle be translated from its pivot point in its local space ?
  57851. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57852. * Default : false
  57853. */
  57854. this.translateFromPivot = false;
  57855. /**
  57856. * Is the particle active or not ?
  57857. */
  57858. this.alive = true;
  57859. /**
  57860. * Is the particle visible or not ?
  57861. */
  57862. this.isVisible = true;
  57863. /**
  57864. * Index of this particle in the global "positions" array (Internal use)
  57865. */
  57866. this._pos = 0;
  57867. /**
  57868. * Index of this particle in the global "indices" array (Internal use)
  57869. */
  57870. this._ind = 0;
  57871. /**
  57872. * ModelShape id of this particle
  57873. */
  57874. this.shapeId = 0;
  57875. /**
  57876. * Index of the particle in its shape id (Internal use)
  57877. */
  57878. this.idxInShape = 0;
  57879. /**
  57880. * Still set as invisible in order to skip useless computations (Internal use)
  57881. */
  57882. this._stillInvisible = false;
  57883. /**
  57884. * Last computed particle rotation matrix
  57885. */
  57886. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57887. /**
  57888. * Parent particle Id, if any.
  57889. * Default null.
  57890. */
  57891. this.parentId = null;
  57892. /**
  57893. * Internal global position in the SPS.
  57894. */
  57895. this._globalPosition = BABYLON.Vector3.Zero();
  57896. this.idx = particleIndex;
  57897. this._pos = positionIndex;
  57898. this._ind = indiceIndex;
  57899. this._model = model;
  57900. this.shapeId = shapeId;
  57901. this.idxInShape = idxInShape;
  57902. this._sps = sps;
  57903. if (modelBoundingInfo) {
  57904. this._modelBoundingInfo = modelBoundingInfo;
  57905. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57906. }
  57907. }
  57908. Object.defineProperty(SolidParticle.prototype, "scale", {
  57909. /**
  57910. * Legacy support, changed scale to scaling
  57911. */
  57912. get: function () {
  57913. return this.scaling;
  57914. },
  57915. /**
  57916. * Legacy support, changed scale to scaling
  57917. */
  57918. set: function (scale) {
  57919. this.scaling = scale;
  57920. },
  57921. enumerable: true,
  57922. configurable: true
  57923. });
  57924. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57925. /**
  57926. * Legacy support, changed quaternion to rotationQuaternion
  57927. */
  57928. get: function () {
  57929. return this.rotationQuaternion;
  57930. },
  57931. /**
  57932. * Legacy support, changed quaternion to rotationQuaternion
  57933. */
  57934. set: function (q) {
  57935. this.rotationQuaternion = q;
  57936. },
  57937. enumerable: true,
  57938. configurable: true
  57939. });
  57940. /**
  57941. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57942. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57943. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57944. * @returns true if it intersects
  57945. */
  57946. SolidParticle.prototype.intersectsMesh = function (target) {
  57947. if (!this._boundingInfo || !target._boundingInfo) {
  57948. return false;
  57949. }
  57950. if (this._sps._bSphereOnly) {
  57951. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57952. }
  57953. return this._boundingInfo.intersects(target._boundingInfo, false);
  57954. };
  57955. return SolidParticle;
  57956. }());
  57957. BABYLON.SolidParticle = SolidParticle;
  57958. /**
  57959. * Represents the shape of the model used by one particle of a solid particle system.
  57960. * SPS internal tool, don't use it manually.
  57961. */
  57962. var ModelShape = /** @class */ (function () {
  57963. /**
  57964. * 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.
  57965. * SPS internal tool, don't use it manually.
  57966. * @hidden
  57967. */
  57968. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57969. /**
  57970. * length of the shape in the model indices array (internal use)
  57971. */
  57972. this._indicesLength = 0;
  57973. this.shapeID = id;
  57974. this._shape = shape;
  57975. this._indicesLength = indicesLength;
  57976. this._shapeUV = shapeUV;
  57977. this._positionFunction = posFunction;
  57978. this._vertexFunction = vtxFunction;
  57979. }
  57980. return ModelShape;
  57981. }());
  57982. BABYLON.ModelShape = ModelShape;
  57983. /**
  57984. * Represents a Depth Sorted Particle in the solid particle system.
  57985. */
  57986. var DepthSortedParticle = /** @class */ (function () {
  57987. function DepthSortedParticle() {
  57988. /**
  57989. * Index of the particle in the "indices" array
  57990. */
  57991. this.ind = 0;
  57992. /**
  57993. * Length of the particle shape in the "indices" array
  57994. */
  57995. this.indicesLength = 0;
  57996. /**
  57997. * Squared distance from the particle to the camera
  57998. */
  57999. this.sqDistance = 0.0;
  58000. }
  58001. return DepthSortedParticle;
  58002. }());
  58003. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58004. })(BABYLON || (BABYLON = {}));
  58005. //# sourceMappingURL=babylon.solidParticle.js.map
  58006. var BABYLON;
  58007. (function (BABYLON) {
  58008. /**
  58009. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58010. *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.
  58011. * The SPS is also a particle system. It provides some methods to manage the particles.
  58012. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58013. *
  58014. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58015. */
  58016. var SolidParticleSystem = /** @class */ (function () {
  58017. /**
  58018. * Creates a SPS (Solid Particle System) object.
  58019. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58020. * @param scene (Scene) is the scene in which the SPS is added.
  58021. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58022. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58023. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58024. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58025. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58026. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58027. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58028. */
  58029. function SolidParticleSystem(name, scene, options) {
  58030. /**
  58031. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58032. * Example : var p = SPS.particles[i];
  58033. */
  58034. this.particles = new Array();
  58035. /**
  58036. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58037. */
  58038. this.nbParticles = 0;
  58039. /**
  58040. * If the particles must ever face the camera (default false). Useful for planar particles.
  58041. */
  58042. this.billboard = false;
  58043. /**
  58044. * Recompute normals when adding a shape
  58045. */
  58046. this.recomputeNormals = true;
  58047. /**
  58048. * This a counter ofr your own usage. It's not set by any SPS functions.
  58049. */
  58050. this.counter = 0;
  58051. /**
  58052. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58053. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58054. */
  58055. this.vars = {};
  58056. /**
  58057. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58058. */
  58059. this._bSphereOnly = false;
  58060. /**
  58061. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58062. */
  58063. this._bSphereRadiusFactor = 1.0;
  58064. this._positions = new Array();
  58065. this._indices = new Array();
  58066. this._normals = new Array();
  58067. this._colors = new Array();
  58068. this._uvs = new Array();
  58069. this._index = 0; // indices index
  58070. this._updatable = true;
  58071. this._pickable = false;
  58072. this._isVisibilityBoxLocked = false;
  58073. this._alwaysVisible = false;
  58074. this._depthSort = false;
  58075. this._shapeCounter = 0;
  58076. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58077. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58078. this._computeParticleColor = true;
  58079. this._computeParticleTexture = true;
  58080. this._computeParticleRotation = true;
  58081. this._computeParticleVertex = false;
  58082. this._computeBoundingBox = false;
  58083. this._depthSortParticles = true;
  58084. this._cam_axisZ = BABYLON.Vector3.Zero();
  58085. this._cam_axisY = BABYLON.Vector3.Zero();
  58086. this._cam_axisX = BABYLON.Vector3.Zero();
  58087. this._axisZ = BABYLON.Axis.Z;
  58088. this._camDir = BABYLON.Vector3.Zero();
  58089. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58090. this._rotMatrix = new BABYLON.Matrix();
  58091. this._invertMatrix = new BABYLON.Matrix();
  58092. this._rotated = BABYLON.Vector3.Zero();
  58093. this._quaternion = new BABYLON.Quaternion();
  58094. this._vertex = BABYLON.Vector3.Zero();
  58095. this._normal = BABYLON.Vector3.Zero();
  58096. this._yaw = 0.0;
  58097. this._pitch = 0.0;
  58098. this._roll = 0.0;
  58099. this._halfroll = 0.0;
  58100. this._halfpitch = 0.0;
  58101. this._halfyaw = 0.0;
  58102. this._sinRoll = 0.0;
  58103. this._cosRoll = 0.0;
  58104. this._sinPitch = 0.0;
  58105. this._cosPitch = 0.0;
  58106. this._sinYaw = 0.0;
  58107. this._cosYaw = 0.0;
  58108. this._mustUnrotateFixedNormals = false;
  58109. this._minimum = BABYLON.Vector3.Zero();
  58110. this._maximum = BABYLON.Vector3.Zero();
  58111. this._minBbox = BABYLON.Vector3.Zero();
  58112. this._maxBbox = BABYLON.Vector3.Zero();
  58113. this._particlesIntersect = false;
  58114. this._depthSortFunction = function (p1, p2) {
  58115. return (p2.sqDistance - p1.sqDistance);
  58116. };
  58117. this._needs32Bits = false;
  58118. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58119. this._scaledPivot = BABYLON.Vector3.Zero();
  58120. this._particleHasParent = false;
  58121. this.name = name;
  58122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58123. this._camera = scene.activeCamera;
  58124. this._pickable = options ? options.isPickable : false;
  58125. this._depthSort = options ? options.enableDepthSort : false;
  58126. this._particlesIntersect = options ? options.particleIntersection : false;
  58127. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58128. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58129. if (options && options.updatable) {
  58130. this._updatable = options.updatable;
  58131. }
  58132. else {
  58133. this._updatable = true;
  58134. }
  58135. if (this._pickable) {
  58136. this.pickedParticles = [];
  58137. }
  58138. if (this._depthSort) {
  58139. this.depthSortedParticles = [];
  58140. }
  58141. }
  58142. /**
  58143. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58144. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58145. * @returns the created mesh
  58146. */
  58147. SolidParticleSystem.prototype.buildMesh = function () {
  58148. if (this.nbParticles === 0) {
  58149. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58150. this.addShape(triangle, 1);
  58151. triangle.dispose();
  58152. }
  58153. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58154. this._positions32 = new Float32Array(this._positions);
  58155. this._uvs32 = new Float32Array(this._uvs);
  58156. this._colors32 = new Float32Array(this._colors);
  58157. if (this.recomputeNormals) {
  58158. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58159. }
  58160. this._normals32 = new Float32Array(this._normals);
  58161. this._fixedNormal32 = new Float32Array(this._normals);
  58162. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58163. this._unrotateFixedNormals();
  58164. }
  58165. var vertexData = new BABYLON.VertexData();
  58166. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58167. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58168. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58169. if (this._uvs32.length > 0) {
  58170. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58171. }
  58172. if (this._colors32.length > 0) {
  58173. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58174. }
  58175. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58176. vertexData.applyToMesh(mesh, this._updatable);
  58177. this.mesh = mesh;
  58178. this.mesh.isPickable = this._pickable;
  58179. // free memory
  58180. if (!this._depthSort) {
  58181. this._indices = null;
  58182. }
  58183. this._positions = null;
  58184. this._normals = null;
  58185. this._uvs = null;
  58186. this._colors = null;
  58187. if (!this._updatable) {
  58188. this.particles.length = 0;
  58189. }
  58190. return mesh;
  58191. };
  58192. /**
  58193. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58194. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58195. * Thus the particles generated from `digest()` have their property `position` set yet.
  58196. * @param mesh ( Mesh ) is the mesh to be digested
  58197. * @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
  58198. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58199. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58200. * @returns the current SPS
  58201. */
  58202. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58203. var size = (options && options.facetNb) || 1;
  58204. var number = (options && options.number) || 0;
  58205. var delta = (options && options.delta) || 0;
  58206. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58207. var meshInd = mesh.getIndices();
  58208. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58209. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58210. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58211. var f = 0; // facet counter
  58212. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58213. // compute size from number
  58214. if (number) {
  58215. number = (number > totalFacets) ? totalFacets : number;
  58216. size = Math.round(totalFacets / number);
  58217. delta = 0;
  58218. }
  58219. else {
  58220. size = (size > totalFacets) ? totalFacets : size;
  58221. }
  58222. var facetPos = []; // submesh positions
  58223. var facetInd = []; // submesh indices
  58224. var facetUV = []; // submesh UV
  58225. var facetCol = []; // submesh colors
  58226. var barycenter = BABYLON.Vector3.Zero();
  58227. var sizeO = size;
  58228. while (f < totalFacets) {
  58229. size = sizeO + Math.floor((1 + delta) * Math.random());
  58230. if (f > totalFacets - size) {
  58231. size = totalFacets - f;
  58232. }
  58233. // reset temp arrays
  58234. facetPos.length = 0;
  58235. facetInd.length = 0;
  58236. facetUV.length = 0;
  58237. facetCol.length = 0;
  58238. // iterate over "size" facets
  58239. var fi = 0;
  58240. for (var j = f * 3; j < (f + size) * 3; j++) {
  58241. facetInd.push(fi);
  58242. var i = meshInd[j];
  58243. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58244. if (meshUV) {
  58245. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58246. }
  58247. if (meshCol) {
  58248. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58249. }
  58250. fi++;
  58251. }
  58252. // create a model shape for each single particle
  58253. var idx = this.nbParticles;
  58254. var shape = this._posToShape(facetPos);
  58255. var shapeUV = this._uvsToShapeUV(facetUV);
  58256. // compute the barycenter of the shape
  58257. var v;
  58258. for (v = 0; v < shape.length; v++) {
  58259. barycenter.addInPlace(shape[v]);
  58260. }
  58261. barycenter.scaleInPlace(1 / shape.length);
  58262. // shift the shape from its barycenter to the origin
  58263. for (v = 0; v < shape.length; v++) {
  58264. shape[v].subtractInPlace(barycenter);
  58265. }
  58266. var bInfo;
  58267. if (this._particlesIntersect) {
  58268. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58269. }
  58270. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58271. // add the particle in the SPS
  58272. var currentPos = this._positions.length;
  58273. var currentInd = this._indices.length;
  58274. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58275. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58276. // initialize the particle position
  58277. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58278. this._index += shape.length;
  58279. idx++;
  58280. this.nbParticles++;
  58281. this._shapeCounter++;
  58282. f += size;
  58283. }
  58284. return this;
  58285. };
  58286. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58287. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58288. var index = 0;
  58289. var idx = 0;
  58290. for (var p = 0; p < this.particles.length; p++) {
  58291. this._particle = this.particles[p];
  58292. this._shape = this._particle._model._shape;
  58293. if (this._particle.rotationQuaternion) {
  58294. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58295. }
  58296. else {
  58297. this._yaw = this._particle.rotation.y;
  58298. this._pitch = this._particle.rotation.x;
  58299. this._roll = this._particle.rotation.z;
  58300. this._quaternionRotationYPR();
  58301. }
  58302. this._quaternionToRotationMatrix();
  58303. this._rotMatrix.invertToRef(this._invertMatrix);
  58304. for (var pt = 0; pt < this._shape.length; pt++) {
  58305. idx = index + pt * 3;
  58306. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58307. this._fixedNormal32[idx] = this._normal.x;
  58308. this._fixedNormal32[idx + 1] = this._normal.y;
  58309. this._fixedNormal32[idx + 2] = this._normal.z;
  58310. }
  58311. index = idx + 3;
  58312. }
  58313. };
  58314. //reset copy
  58315. SolidParticleSystem.prototype._resetCopy = function () {
  58316. this._copy.position.x = 0;
  58317. this._copy.position.y = 0;
  58318. this._copy.position.z = 0;
  58319. this._copy.rotation.x = 0;
  58320. this._copy.rotation.y = 0;
  58321. this._copy.rotation.z = 0;
  58322. this._copy.rotationQuaternion = null;
  58323. this._copy.scaling.x = 1.0;
  58324. this._copy.scaling.y = 1.0;
  58325. this._copy.scaling.z = 1.0;
  58326. this._copy.uvs.x = 0;
  58327. this._copy.uvs.y = 0;
  58328. this._copy.uvs.z = 1.0;
  58329. this._copy.uvs.w = 1.0;
  58330. this._copy.color = null;
  58331. this._copy.translateFromPivot = false;
  58332. };
  58333. // _meshBuilder : inserts the shape model in the global SPS mesh
  58334. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58335. var i;
  58336. var u = 0;
  58337. var c = 0;
  58338. var n = 0;
  58339. this._resetCopy();
  58340. if (options && options.positionFunction) { // call to custom positionFunction
  58341. options.positionFunction(this._copy, idx, idxInShape);
  58342. this._mustUnrotateFixedNormals = true;
  58343. }
  58344. if (this._copy.rotationQuaternion) {
  58345. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58346. }
  58347. else {
  58348. this._yaw = this._copy.rotation.y;
  58349. this._pitch = this._copy.rotation.x;
  58350. this._roll = this._copy.rotation.z;
  58351. this._quaternionRotationYPR();
  58352. }
  58353. this._quaternionToRotationMatrix();
  58354. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58355. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58356. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58357. if (this._copy.translateFromPivot) {
  58358. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58359. }
  58360. else {
  58361. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58362. }
  58363. for (i = 0; i < shape.length; i++) {
  58364. this._vertex.x = shape[i].x;
  58365. this._vertex.y = shape[i].y;
  58366. this._vertex.z = shape[i].z;
  58367. if (options && options.vertexFunction) {
  58368. options.vertexFunction(this._copy, this._vertex, i);
  58369. }
  58370. this._vertex.x *= this._copy.scaling.x;
  58371. this._vertex.y *= this._copy.scaling.y;
  58372. this._vertex.z *= this._copy.scaling.z;
  58373. this._vertex.x -= this._scaledPivot.x;
  58374. this._vertex.y -= this._scaledPivot.y;
  58375. this._vertex.z -= this._scaledPivot.z;
  58376. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58377. this._rotated.addInPlace(this._pivotBackTranslation);
  58378. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58379. if (meshUV) {
  58380. 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);
  58381. u += 2;
  58382. }
  58383. if (this._copy.color) {
  58384. this._color = this._copy.color;
  58385. }
  58386. else if (meshCol && meshCol[c] !== undefined) {
  58387. this._color.r = meshCol[c];
  58388. this._color.g = meshCol[c + 1];
  58389. this._color.b = meshCol[c + 2];
  58390. this._color.a = meshCol[c + 3];
  58391. }
  58392. else {
  58393. this._color.r = 1.0;
  58394. this._color.g = 1.0;
  58395. this._color.b = 1.0;
  58396. this._color.a = 1.0;
  58397. }
  58398. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58399. c += 4;
  58400. if (!this.recomputeNormals && meshNor) {
  58401. this._normal.x = meshNor[n];
  58402. this._normal.y = meshNor[n + 1];
  58403. this._normal.z = meshNor[n + 2];
  58404. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58405. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58406. n += 3;
  58407. }
  58408. }
  58409. for (i = 0; i < meshInd.length; i++) {
  58410. var current_ind = p + meshInd[i];
  58411. indices.push(current_ind);
  58412. if (current_ind > 65535) {
  58413. this._needs32Bits = true;
  58414. }
  58415. }
  58416. if (this._pickable) {
  58417. var nbfaces = meshInd.length / 3;
  58418. for (i = 0; i < nbfaces; i++) {
  58419. this.pickedParticles.push({ idx: idx, faceId: i });
  58420. }
  58421. }
  58422. if (this._depthSort) {
  58423. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58424. }
  58425. return this._copy;
  58426. };
  58427. // returns a shape array from positions array
  58428. SolidParticleSystem.prototype._posToShape = function (positions) {
  58429. var shape = [];
  58430. for (var i = 0; i < positions.length; i += 3) {
  58431. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58432. }
  58433. return shape;
  58434. };
  58435. // returns a shapeUV array from a Vector4 uvs
  58436. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58437. var shapeUV = [];
  58438. if (uvs) {
  58439. for (var i = 0; i < uvs.length; i++)
  58440. shapeUV.push(uvs[i]);
  58441. }
  58442. return shapeUV;
  58443. };
  58444. // adds a new particle object in the particles array
  58445. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58446. if (bInfo === void 0) { bInfo = null; }
  58447. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58448. this.particles.push(sp);
  58449. return sp;
  58450. };
  58451. /**
  58452. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58453. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58454. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58455. * @param nb (positive integer) the number of particles to be created from this model
  58456. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58457. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58458. * @returns the number of shapes in the system
  58459. */
  58460. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58461. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58462. var meshInd = mesh.getIndices();
  58463. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58464. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58465. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58466. var bbInfo;
  58467. if (this._particlesIntersect) {
  58468. bbInfo = mesh.getBoundingInfo();
  58469. }
  58470. var shape = this._posToShape(meshPos);
  58471. var shapeUV = this._uvsToShapeUV(meshUV);
  58472. var posfunc = options ? options.positionFunction : null;
  58473. var vtxfunc = options ? options.vertexFunction : null;
  58474. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58475. // particles
  58476. var sp;
  58477. var currentCopy;
  58478. var idx = this.nbParticles;
  58479. for (var i = 0; i < nb; i++) {
  58480. var currentPos = this._positions.length;
  58481. var currentInd = this._indices.length;
  58482. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58483. if (this._updatable) {
  58484. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58485. sp.position.copyFrom(currentCopy.position);
  58486. sp.rotation.copyFrom(currentCopy.rotation);
  58487. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58488. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58489. }
  58490. if (currentCopy.color && sp.color) {
  58491. sp.color.copyFrom(currentCopy.color);
  58492. }
  58493. sp.scaling.copyFrom(currentCopy.scaling);
  58494. sp.uvs.copyFrom(currentCopy.uvs);
  58495. }
  58496. this._index += shape.length;
  58497. idx++;
  58498. }
  58499. this.nbParticles += nb;
  58500. this._shapeCounter++;
  58501. return this._shapeCounter - 1;
  58502. };
  58503. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58504. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58505. this._resetCopy();
  58506. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58507. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58508. }
  58509. if (this._copy.rotationQuaternion) {
  58510. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58511. }
  58512. else {
  58513. this._yaw = this._copy.rotation.y;
  58514. this._pitch = this._copy.rotation.x;
  58515. this._roll = this._copy.rotation.z;
  58516. this._quaternionRotationYPR();
  58517. }
  58518. this._quaternionToRotationMatrix();
  58519. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58520. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58521. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58522. if (this._copy.translateFromPivot) {
  58523. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58524. }
  58525. else {
  58526. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58527. }
  58528. this._shape = particle._model._shape;
  58529. for (var pt = 0; pt < this._shape.length; pt++) {
  58530. this._vertex.x = this._shape[pt].x;
  58531. this._vertex.y = this._shape[pt].y;
  58532. this._vertex.z = this._shape[pt].z;
  58533. if (particle._model._vertexFunction) {
  58534. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58535. }
  58536. this._vertex.x *= this._copy.scaling.x;
  58537. this._vertex.y *= this._copy.scaling.y;
  58538. this._vertex.z *= this._copy.scaling.z;
  58539. this._vertex.x -= this._scaledPivot.x;
  58540. this._vertex.y -= this._scaledPivot.y;
  58541. this._vertex.z -= this._scaledPivot.z;
  58542. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58543. this._rotated.addInPlace(this._pivotBackTranslation);
  58544. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58545. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58546. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58547. }
  58548. particle.position.x = 0.0;
  58549. particle.position.y = 0.0;
  58550. particle.position.z = 0.0;
  58551. particle.rotation.x = 0.0;
  58552. particle.rotation.y = 0.0;
  58553. particle.rotation.z = 0.0;
  58554. particle.rotationQuaternion = null;
  58555. particle.scaling.x = 1.0;
  58556. particle.scaling.y = 1.0;
  58557. particle.scaling.z = 1.0;
  58558. particle.uvs.x = 0.0;
  58559. particle.uvs.y = 0.0;
  58560. particle.uvs.z = 1.0;
  58561. particle.uvs.w = 1.0;
  58562. particle.pivot.x = 0.0;
  58563. particle.pivot.y = 0.0;
  58564. particle.pivot.z = 0.0;
  58565. particle.translateFromPivot = false;
  58566. particle.parentId = null;
  58567. };
  58568. /**
  58569. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58570. * @returns the SPS.
  58571. */
  58572. SolidParticleSystem.prototype.rebuildMesh = function () {
  58573. for (var p = 0; p < this.particles.length; p++) {
  58574. this._rebuildParticle(this.particles[p]);
  58575. }
  58576. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58577. return this;
  58578. };
  58579. /**
  58580. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58581. * This method calls `updateParticle()` for each particle of the SPS.
  58582. * For an animated SPS, it is usually called within the render loop.
  58583. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58584. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58585. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58586. * @returns the SPS.
  58587. */
  58588. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58589. if (start === void 0) { start = 0; }
  58590. if (end === void 0) { end = this.nbParticles - 1; }
  58591. if (update === void 0) { update = true; }
  58592. if (!this._updatable) {
  58593. return this;
  58594. }
  58595. // custom beforeUpdate
  58596. this.beforeUpdateParticles(start, end, update);
  58597. this._cam_axisX.x = 1.0;
  58598. this._cam_axisX.y = 0.0;
  58599. this._cam_axisX.z = 0.0;
  58600. this._cam_axisY.x = 0.0;
  58601. this._cam_axisY.y = 1.0;
  58602. this._cam_axisY.z = 0.0;
  58603. this._cam_axisZ.x = 0.0;
  58604. this._cam_axisZ.y = 0.0;
  58605. this._cam_axisZ.z = 1.0;
  58606. // cases when the World Matrix is to be computed first
  58607. if (this.billboard || this._depthSort) {
  58608. this.mesh.computeWorldMatrix(true);
  58609. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58610. }
  58611. // if the particles will always face the camera
  58612. if (this.billboard) {
  58613. // compute the camera position and un-rotate it by the current mesh rotation
  58614. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58615. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58616. this._cam_axisZ.normalize();
  58617. // same for camera up vector extracted from the cam view matrix
  58618. var view = this._camera.getViewMatrix(true);
  58619. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58620. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58621. this._cam_axisY.normalize();
  58622. this._cam_axisX.normalize();
  58623. }
  58624. // if depthSort, compute the camera global position in the mesh local system
  58625. if (this._depthSort) {
  58626. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58627. }
  58628. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58629. var idx = 0; // current position index in the global array positions32
  58630. var index = 0; // position start index in the global array positions32 of the current particle
  58631. var colidx = 0; // current color index in the global array colors32
  58632. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58633. var uvidx = 0; // current uv index in the global array uvs32
  58634. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58635. var pt = 0; // current index in the particle model shape
  58636. if (this.mesh.isFacetDataEnabled) {
  58637. this._computeBoundingBox = true;
  58638. }
  58639. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58640. if (this._computeBoundingBox) {
  58641. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58642. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58643. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58644. }
  58645. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58646. if (this.mesh._boundingInfo) {
  58647. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58648. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58649. }
  58650. }
  58651. }
  58652. // particle loop
  58653. index = this.particles[start]._pos;
  58654. var vpos = (index / 3) | 0;
  58655. colorIndex = vpos * 4;
  58656. uvIndex = vpos * 2;
  58657. for (var p = start; p <= end; p++) {
  58658. this._particle = this.particles[p];
  58659. this._shape = this._particle._model._shape;
  58660. this._shapeUV = this._particle._model._shapeUV;
  58661. // call to custom user function to update the particle properties
  58662. this.updateParticle(this._particle);
  58663. // camera-particle distance for depth sorting
  58664. if (this._depthSort && this._depthSortParticles) {
  58665. var dsp = this.depthSortedParticles[p];
  58666. dsp.ind = this._particle._ind;
  58667. dsp.indicesLength = this._particle._model._indicesLength;
  58668. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58669. }
  58670. // skip the computations for inactive or already invisible particles
  58671. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58672. // increment indexes for the next particle
  58673. pt = this._shape.length;
  58674. index += pt * 3;
  58675. colorIndex += pt * 4;
  58676. uvIndex += pt * 2;
  58677. continue;
  58678. }
  58679. if (this._particle.isVisible) {
  58680. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58681. this._particleHasParent = (this._particle.parentId !== null);
  58682. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58683. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58684. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58685. // particle rotation matrix
  58686. if (this.billboard) {
  58687. this._particle.rotation.x = 0.0;
  58688. this._particle.rotation.y = 0.0;
  58689. }
  58690. if (this._computeParticleRotation || this.billboard) {
  58691. if (this._particle.rotationQuaternion) {
  58692. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58693. }
  58694. else {
  58695. this._yaw = this._particle.rotation.y;
  58696. this._pitch = this._particle.rotation.x;
  58697. this._roll = this._particle.rotation.z;
  58698. this._quaternionRotationYPR();
  58699. }
  58700. this._quaternionToRotationMatrix();
  58701. }
  58702. if (this._particleHasParent) {
  58703. this._parent = this.particles[this._particle.parentId];
  58704. 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];
  58705. 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];
  58706. 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];
  58707. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58708. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58709. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58710. if (this._computeParticleRotation || this.billboard) {
  58711. 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];
  58712. 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];
  58713. 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];
  58714. 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];
  58715. 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];
  58716. 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];
  58717. 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];
  58718. 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];
  58719. 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];
  58720. }
  58721. }
  58722. else {
  58723. this._particle._globalPosition.x = this._particle.position.x;
  58724. this._particle._globalPosition.y = this._particle.position.y;
  58725. this._particle._globalPosition.z = this._particle.position.z;
  58726. if (this._computeParticleRotation || this.billboard) {
  58727. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58728. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58729. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58730. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58731. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58732. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58733. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58734. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58735. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58736. }
  58737. }
  58738. if (this._particle.translateFromPivot) {
  58739. this._pivotBackTranslation.x = 0.0;
  58740. this._pivotBackTranslation.y = 0.0;
  58741. this._pivotBackTranslation.z = 0.0;
  58742. }
  58743. else {
  58744. this._pivotBackTranslation.x = this._scaledPivot.x;
  58745. this._pivotBackTranslation.y = this._scaledPivot.y;
  58746. this._pivotBackTranslation.z = this._scaledPivot.z;
  58747. }
  58748. // particle vertex loop
  58749. for (pt = 0; pt < this._shape.length; pt++) {
  58750. idx = index + pt * 3;
  58751. colidx = colorIndex + pt * 4;
  58752. uvidx = uvIndex + pt * 2;
  58753. this._vertex.x = this._shape[pt].x;
  58754. this._vertex.y = this._shape[pt].y;
  58755. this._vertex.z = this._shape[pt].z;
  58756. if (this._computeParticleVertex) {
  58757. this.updateParticleVertex(this._particle, this._vertex, pt);
  58758. }
  58759. // positions
  58760. this._vertex.x *= this._particle.scaling.x;
  58761. this._vertex.y *= this._particle.scaling.y;
  58762. this._vertex.z *= this._particle.scaling.z;
  58763. this._vertex.x -= this._scaledPivot.x;
  58764. this._vertex.y -= this._scaledPivot.y;
  58765. this._vertex.z -= this._scaledPivot.z;
  58766. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58767. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58768. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58769. this._rotated.x += this._pivotBackTranslation.x;
  58770. this._rotated.y += this._pivotBackTranslation.y;
  58771. this._rotated.z += this._pivotBackTranslation.z;
  58772. 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;
  58773. 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;
  58774. 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;
  58775. if (this._computeBoundingBox) {
  58776. if (this._positions32[idx] < this._minimum.x) {
  58777. this._minimum.x = this._positions32[idx];
  58778. }
  58779. if (this._positions32[idx] > this._maximum.x) {
  58780. this._maximum.x = this._positions32[idx];
  58781. }
  58782. if (this._positions32[idx + 1] < this._minimum.y) {
  58783. this._minimum.y = this._positions32[idx + 1];
  58784. }
  58785. if (this._positions32[idx + 1] > this._maximum.y) {
  58786. this._maximum.y = this._positions32[idx + 1];
  58787. }
  58788. if (this._positions32[idx + 2] < this._minimum.z) {
  58789. this._minimum.z = this._positions32[idx + 2];
  58790. }
  58791. if (this._positions32[idx + 2] > this._maximum.z) {
  58792. this._maximum.z = this._positions32[idx + 2];
  58793. }
  58794. }
  58795. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58796. if (!this._computeParticleVertex) {
  58797. this._normal.x = this._fixedNormal32[idx];
  58798. this._normal.y = this._fixedNormal32[idx + 1];
  58799. this._normal.z = this._fixedNormal32[idx + 2];
  58800. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58801. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58802. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58803. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58804. 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;
  58805. 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;
  58806. }
  58807. if (this._computeParticleColor && this._particle.color) {
  58808. this._colors32[colidx] = this._particle.color.r;
  58809. this._colors32[colidx + 1] = this._particle.color.g;
  58810. this._colors32[colidx + 2] = this._particle.color.b;
  58811. this._colors32[colidx + 3] = this._particle.color.a;
  58812. }
  58813. if (this._computeParticleTexture) {
  58814. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58815. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58816. }
  58817. }
  58818. }
  58819. // particle just set invisible : scaled to zero and positioned at the origin
  58820. else {
  58821. this._particle._stillInvisible = true; // mark the particle as invisible
  58822. for (pt = 0; pt < this._shape.length; pt++) {
  58823. idx = index + pt * 3;
  58824. colidx = colorIndex + pt * 4;
  58825. uvidx = uvIndex + pt * 2;
  58826. this._positions32[idx] = 0.0;
  58827. this._positions32[idx + 1] = 0.0;
  58828. this._positions32[idx + 2] = 0.0;
  58829. this._normals32[idx] = 0.0;
  58830. this._normals32[idx + 1] = 0.0;
  58831. this._normals32[idx + 2] = 0.0;
  58832. if (this._computeParticleColor && this._particle.color) {
  58833. this._colors32[colidx] = this._particle.color.r;
  58834. this._colors32[colidx + 1] = this._particle.color.g;
  58835. this._colors32[colidx + 2] = this._particle.color.b;
  58836. this._colors32[colidx + 3] = this._particle.color.a;
  58837. }
  58838. if (this._computeParticleTexture) {
  58839. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58840. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58841. }
  58842. }
  58843. }
  58844. // if the particle intersections must be computed : update the bbInfo
  58845. if (this._particlesIntersect) {
  58846. var bInfo = this._particle._boundingInfo;
  58847. var bBox = bInfo.boundingBox;
  58848. var bSphere = bInfo.boundingSphere;
  58849. if (!this._bSphereOnly) {
  58850. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58851. for (var b = 0; b < bBox.vectors.length; b++) {
  58852. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58853. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58854. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58855. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58856. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58857. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58858. 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;
  58859. 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;
  58860. 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;
  58861. }
  58862. bBox._update(this.mesh._worldMatrix);
  58863. }
  58864. // place and scale the particle bouding sphere in the SPS local system, then update it
  58865. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58866. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58867. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58868. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58869. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58870. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58871. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58872. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58873. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58874. 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));
  58875. bSphere._update(this.mesh._worldMatrix);
  58876. }
  58877. // increment indexes for the next particle
  58878. index = idx + 3;
  58879. colorIndex = colidx + 4;
  58880. uvIndex = uvidx + 2;
  58881. }
  58882. // if the VBO must be updated
  58883. if (update) {
  58884. if (this._computeParticleColor) {
  58885. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58886. }
  58887. if (this._computeParticleTexture) {
  58888. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58889. }
  58890. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58891. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58892. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58893. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58894. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58895. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58896. for (var i = 0; i < this._normals32.length; i++) {
  58897. this._fixedNormal32[i] = this._normals32[i];
  58898. }
  58899. }
  58900. if (!this.mesh.areNormalsFrozen) {
  58901. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58902. }
  58903. }
  58904. if (this._depthSort && this._depthSortParticles) {
  58905. this.depthSortedParticles.sort(this._depthSortFunction);
  58906. var dspl = this.depthSortedParticles.length;
  58907. var sorted = 0;
  58908. var lind = 0;
  58909. var sind = 0;
  58910. var sid = 0;
  58911. for (sorted = 0; sorted < dspl; sorted++) {
  58912. lind = this.depthSortedParticles[sorted].indicesLength;
  58913. sind = this.depthSortedParticles[sorted].ind;
  58914. for (var i = 0; i < lind; i++) {
  58915. this._indices32[sid] = this._indices[sind + i];
  58916. sid++;
  58917. }
  58918. }
  58919. this.mesh.updateIndices(this._indices32);
  58920. }
  58921. }
  58922. if (this._computeBoundingBox) {
  58923. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58924. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58925. }
  58926. this.afterUpdateParticles(start, end, update);
  58927. return this;
  58928. };
  58929. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58930. this._halfroll = this._roll * 0.5;
  58931. this._halfpitch = this._pitch * 0.5;
  58932. this._halfyaw = this._yaw * 0.5;
  58933. this._sinRoll = Math.sin(this._halfroll);
  58934. this._cosRoll = Math.cos(this._halfroll);
  58935. this._sinPitch = Math.sin(this._halfpitch);
  58936. this._cosPitch = Math.cos(this._halfpitch);
  58937. this._sinYaw = Math.sin(this._halfyaw);
  58938. this._cosYaw = Math.cos(this._halfyaw);
  58939. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58940. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58941. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58942. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58943. };
  58944. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58945. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58946. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58947. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58948. this._rotMatrix.m[3] = 0;
  58949. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58950. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58951. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58952. this._rotMatrix.m[7] = 0;
  58953. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58954. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58955. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58956. this._rotMatrix.m[11] = 0;
  58957. this._rotMatrix.m[12] = 0;
  58958. this._rotMatrix.m[13] = 0;
  58959. this._rotMatrix.m[14] = 0;
  58960. this._rotMatrix.m[15] = 1.0;
  58961. };
  58962. /**
  58963. * Disposes the SPS.
  58964. */
  58965. SolidParticleSystem.prototype.dispose = function () {
  58966. this.mesh.dispose();
  58967. this.vars = null;
  58968. // drop references to internal big arrays for the GC
  58969. this._positions = null;
  58970. this._indices = null;
  58971. this._normals = null;
  58972. this._uvs = null;
  58973. this._colors = null;
  58974. this._indices32 = null;
  58975. this._positions32 = null;
  58976. this._normals32 = null;
  58977. this._fixedNormal32 = null;
  58978. this._uvs32 = null;
  58979. this._colors32 = null;
  58980. this.pickedParticles = null;
  58981. };
  58982. /**
  58983. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58984. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58985. * @returns the SPS.
  58986. */
  58987. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58988. if (!this._isVisibilityBoxLocked) {
  58989. this.mesh.refreshBoundingInfo();
  58990. }
  58991. return this;
  58992. };
  58993. /**
  58994. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58995. * @param size the size (float) of the visibility box
  58996. * note : this doesn't lock the SPS mesh bounding box.
  58997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58998. */
  58999. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59000. var vis = size / 2;
  59001. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59002. };
  59003. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59004. /**
  59005. * Gets whether the SPS as always visible or not
  59006. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59007. */
  59008. get: function () {
  59009. return this._alwaysVisible;
  59010. },
  59011. /**
  59012. * Sets the SPS as always visible or not
  59013. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59014. */
  59015. set: function (val) {
  59016. this._alwaysVisible = val;
  59017. this.mesh.alwaysSelectAsActiveMesh = val;
  59018. },
  59019. enumerable: true,
  59020. configurable: true
  59021. });
  59022. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59023. /**
  59024. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59025. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59026. */
  59027. get: function () {
  59028. return this._isVisibilityBoxLocked;
  59029. },
  59030. /**
  59031. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59032. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59033. */
  59034. set: function (val) {
  59035. this._isVisibilityBoxLocked = val;
  59036. var boundingInfo = this.mesh.getBoundingInfo();
  59037. boundingInfo.isLocked = val;
  59038. },
  59039. enumerable: true,
  59040. configurable: true
  59041. });
  59042. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59043. /**
  59044. * Gets if `setParticles()` computes the particle rotations or not.
  59045. * Default value : true. The SPS is faster when it's set to false.
  59046. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59047. */
  59048. get: function () {
  59049. return this._computeParticleRotation;
  59050. },
  59051. /**
  59052. * Tells to `setParticles()` to compute the particle rotations or not.
  59053. * Default value : true. The SPS is faster when it's set to false.
  59054. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59055. */
  59056. set: function (val) {
  59057. this._computeParticleRotation = val;
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59063. /**
  59064. * Gets if `setParticles()` computes the particle colors or not.
  59065. * Default value : true. The SPS is faster when it's set to false.
  59066. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59067. */
  59068. get: function () {
  59069. return this._computeParticleColor;
  59070. },
  59071. /**
  59072. * Tells to `setParticles()` to compute the particle colors or not.
  59073. * Default value : true. The SPS is faster when it's set to false.
  59074. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59075. */
  59076. set: function (val) {
  59077. this._computeParticleColor = val;
  59078. },
  59079. enumerable: true,
  59080. configurable: true
  59081. });
  59082. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59083. /**
  59084. * Gets if `setParticles()` computes the particle textures or not.
  59085. * Default value : true. The SPS is faster when it's set to false.
  59086. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59087. */
  59088. get: function () {
  59089. return this._computeParticleTexture;
  59090. },
  59091. set: function (val) {
  59092. this._computeParticleTexture = val;
  59093. },
  59094. enumerable: true,
  59095. configurable: true
  59096. });
  59097. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59098. /**
  59099. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59100. * Default value : false. The SPS is faster when it's set to false.
  59101. * Note : the particle custom vertex positions aren't stored values.
  59102. */
  59103. get: function () {
  59104. return this._computeParticleVertex;
  59105. },
  59106. /**
  59107. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59108. * Default value : false. The SPS is faster when it's set to false.
  59109. * Note : the particle custom vertex positions aren't stored values.
  59110. */
  59111. set: function (val) {
  59112. this._computeParticleVertex = val;
  59113. },
  59114. enumerable: true,
  59115. configurable: true
  59116. });
  59117. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59118. /**
  59119. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59120. */
  59121. get: function () {
  59122. return this._computeBoundingBox;
  59123. },
  59124. /**
  59125. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59126. */
  59127. set: function (val) {
  59128. this._computeBoundingBox = val;
  59129. },
  59130. enumerable: true,
  59131. configurable: true
  59132. });
  59133. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59134. /**
  59135. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59136. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59137. * Default : `true`
  59138. */
  59139. get: function () {
  59140. return this._depthSortParticles;
  59141. },
  59142. /**
  59143. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59144. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59145. * Default : `true`
  59146. */
  59147. set: function (val) {
  59148. this._depthSortParticles = val;
  59149. },
  59150. enumerable: true,
  59151. configurable: true
  59152. });
  59153. // =======================================================================
  59154. // Particle behavior logic
  59155. // these following methods may be overwritten by the user to fit his needs
  59156. /**
  59157. * This function does nothing. It may be overwritten to set all the particle first values.
  59158. * The SPS doesn't call this function, you may have to call it by your own.
  59159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59160. */
  59161. SolidParticleSystem.prototype.initParticles = function () {
  59162. };
  59163. /**
  59164. * This function does nothing. It may be overwritten to recycle a particle.
  59165. * The SPS doesn't call this function, you may have to call it by your own.
  59166. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59167. * @param particle The particle to recycle
  59168. * @returns the recycled particle
  59169. */
  59170. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59171. return particle;
  59172. };
  59173. /**
  59174. * Updates a particle : this function should be overwritten by the user.
  59175. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59176. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59177. * @example : just set a particle position or velocity and recycle conditions
  59178. * @param particle The particle to update
  59179. * @returns the updated particle
  59180. */
  59181. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59182. return particle;
  59183. };
  59184. /**
  59185. * Updates a vertex of a particle : it can be overwritten by the user.
  59186. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59187. * @param particle the current particle
  59188. * @param vertex the current index of the current particle
  59189. * @param pt the index of the current vertex in the particle shape
  59190. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59191. * @example : just set a vertex particle position
  59192. * @returns the updated vertex
  59193. */
  59194. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59195. return vertex;
  59196. };
  59197. /**
  59198. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59199. * This does nothing and may be overwritten by the user.
  59200. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59201. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59202. * @param update the boolean update value actually passed to setParticles()
  59203. */
  59204. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59205. };
  59206. /**
  59207. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59208. * This will be passed three parameters.
  59209. * This does nothing and may be overwritten by the user.
  59210. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59211. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59212. * @param update the boolean update value actually passed to setParticles()
  59213. */
  59214. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59215. };
  59216. return SolidParticleSystem;
  59217. }());
  59218. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59219. })(BABYLON || (BABYLON = {}));
  59220. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59221. var BABYLON;
  59222. (function (BABYLON) {
  59223. var ShaderMaterial = /** @class */ (function (_super) {
  59224. __extends(ShaderMaterial, _super);
  59225. function ShaderMaterial(name, scene, shaderPath, options) {
  59226. var _this = _super.call(this, name, scene) || this;
  59227. _this._textures = {};
  59228. _this._textureArrays = {};
  59229. _this._floats = {};
  59230. _this._ints = {};
  59231. _this._floatsArrays = {};
  59232. _this._colors3 = {};
  59233. _this._colors3Arrays = {};
  59234. _this._colors4 = {};
  59235. _this._vectors2 = {};
  59236. _this._vectors3 = {};
  59237. _this._vectors4 = {};
  59238. _this._matrices = {};
  59239. _this._matrices3x3 = {};
  59240. _this._matrices2x2 = {};
  59241. _this._vectors2Arrays = {};
  59242. _this._vectors3Arrays = {};
  59243. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59244. _this._shaderPath = shaderPath;
  59245. options.needAlphaBlending = options.needAlphaBlending || false;
  59246. options.needAlphaTesting = options.needAlphaTesting || false;
  59247. options.attributes = options.attributes || ["position", "normal", "uv"];
  59248. options.uniforms = options.uniforms || ["worldViewProjection"];
  59249. options.uniformBuffers = options.uniformBuffers || [];
  59250. options.samplers = options.samplers || [];
  59251. options.defines = options.defines || [];
  59252. _this._options = options;
  59253. return _this;
  59254. }
  59255. ShaderMaterial.prototype.getClassName = function () {
  59256. return "ShaderMaterial";
  59257. };
  59258. ShaderMaterial.prototype.needAlphaBlending = function () {
  59259. return this._options.needAlphaBlending;
  59260. };
  59261. ShaderMaterial.prototype.needAlphaTesting = function () {
  59262. return this._options.needAlphaTesting;
  59263. };
  59264. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59265. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59266. this._options.uniforms.push(uniformName);
  59267. }
  59268. };
  59269. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59270. if (this._options.samplers.indexOf(name) === -1) {
  59271. this._options.samplers.push(name);
  59272. }
  59273. this._textures[name] = texture;
  59274. return this;
  59275. };
  59276. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59277. if (this._options.samplers.indexOf(name) === -1) {
  59278. this._options.samplers.push(name);
  59279. }
  59280. this._checkUniform(name);
  59281. this._textureArrays[name] = textures;
  59282. return this;
  59283. };
  59284. ShaderMaterial.prototype.setFloat = function (name, value) {
  59285. this._checkUniform(name);
  59286. this._floats[name] = value;
  59287. return this;
  59288. };
  59289. ShaderMaterial.prototype.setInt = function (name, value) {
  59290. this._checkUniform(name);
  59291. this._ints[name] = value;
  59292. return this;
  59293. };
  59294. ShaderMaterial.prototype.setFloats = function (name, value) {
  59295. this._checkUniform(name);
  59296. this._floatsArrays[name] = value;
  59297. return this;
  59298. };
  59299. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59300. this._checkUniform(name);
  59301. this._colors3[name] = value;
  59302. return this;
  59303. };
  59304. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59305. this._checkUniform(name);
  59306. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59307. color.toArray(arr, arr.length);
  59308. return arr;
  59309. }, []);
  59310. return this;
  59311. };
  59312. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59313. this._checkUniform(name);
  59314. this._colors4[name] = value;
  59315. return this;
  59316. };
  59317. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59318. this._checkUniform(name);
  59319. this._vectors2[name] = value;
  59320. return this;
  59321. };
  59322. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59323. this._checkUniform(name);
  59324. this._vectors3[name] = value;
  59325. return this;
  59326. };
  59327. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59328. this._checkUniform(name);
  59329. this._vectors4[name] = value;
  59330. return this;
  59331. };
  59332. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59333. this._checkUniform(name);
  59334. this._matrices[name] = value;
  59335. return this;
  59336. };
  59337. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59338. this._checkUniform(name);
  59339. this._matrices3x3[name] = value;
  59340. return this;
  59341. };
  59342. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59343. this._checkUniform(name);
  59344. this._matrices2x2[name] = value;
  59345. return this;
  59346. };
  59347. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59348. this._checkUniform(name);
  59349. this._vectors2Arrays[name] = value;
  59350. return this;
  59351. };
  59352. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59353. this._checkUniform(name);
  59354. this._vectors3Arrays[name] = value;
  59355. return this;
  59356. };
  59357. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59358. if (!mesh) {
  59359. return true;
  59360. }
  59361. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59362. return false;
  59363. }
  59364. return false;
  59365. };
  59366. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59367. var scene = this.getScene();
  59368. var engine = scene.getEngine();
  59369. if (!this.checkReadyOnEveryCall) {
  59370. if (this._renderId === scene.getRenderId()) {
  59371. if (this._checkCache(scene, mesh, useInstances)) {
  59372. return true;
  59373. }
  59374. }
  59375. }
  59376. // Instances
  59377. var defines = [];
  59378. var attribs = [];
  59379. var fallbacks = new BABYLON.EffectFallbacks();
  59380. if (useInstances) {
  59381. defines.push("#define INSTANCES");
  59382. }
  59383. for (var index = 0; index < this._options.defines.length; index++) {
  59384. defines.push(this._options.defines[index]);
  59385. }
  59386. for (var index = 0; index < this._options.attributes.length; index++) {
  59387. attribs.push(this._options.attributes[index]);
  59388. }
  59389. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59390. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59391. defines.push("#define VERTEXCOLOR");
  59392. }
  59393. // Bones
  59394. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59397. if (mesh.numBoneInfluencers > 4) {
  59398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59400. }
  59401. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59402. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59403. fallbacks.addCPUSkinningFallback(0, mesh);
  59404. if (this._options.uniforms.indexOf("mBones") === -1) {
  59405. this._options.uniforms.push("mBones");
  59406. }
  59407. }
  59408. else {
  59409. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59410. }
  59411. // Textures
  59412. for (var name in this._textures) {
  59413. if (!this._textures[name].isReady()) {
  59414. return false;
  59415. }
  59416. }
  59417. // Alpha test
  59418. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59419. defines.push("#define ALPHATEST");
  59420. }
  59421. var previousEffect = this._effect;
  59422. var join = defines.join("\n");
  59423. this._effect = engine.createEffect(this._shaderPath, {
  59424. attributes: attribs,
  59425. uniformsNames: this._options.uniforms,
  59426. uniformBuffersNames: this._options.uniformBuffers,
  59427. samplers: this._options.samplers,
  59428. defines: join,
  59429. fallbacks: fallbacks,
  59430. onCompiled: this.onCompiled,
  59431. onError: this.onError
  59432. }, engine);
  59433. if (!this._effect.isReady()) {
  59434. return false;
  59435. }
  59436. if (previousEffect !== this._effect) {
  59437. scene.resetCachedMaterial();
  59438. }
  59439. this._renderId = scene.getRenderId();
  59440. return true;
  59441. };
  59442. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59443. var scene = this.getScene();
  59444. if (!this._effect) {
  59445. return;
  59446. }
  59447. if (this._options.uniforms.indexOf("world") !== -1) {
  59448. this._effect.setMatrix("world", world);
  59449. }
  59450. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59451. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59452. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59453. }
  59454. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59455. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59456. }
  59457. };
  59458. ShaderMaterial.prototype.bind = function (world, mesh) {
  59459. // Std values
  59460. this.bindOnlyWorldMatrix(world);
  59461. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59462. if (this._options.uniforms.indexOf("view") !== -1) {
  59463. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59464. }
  59465. if (this._options.uniforms.indexOf("projection") !== -1) {
  59466. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59467. }
  59468. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59469. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59470. }
  59471. // Bones
  59472. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59473. var name;
  59474. // Texture
  59475. for (name in this._textures) {
  59476. this._effect.setTexture(name, this._textures[name]);
  59477. }
  59478. // Texture arrays
  59479. for (name in this._textureArrays) {
  59480. this._effect.setTextureArray(name, this._textureArrays[name]);
  59481. }
  59482. // Int
  59483. for (name in this._ints) {
  59484. this._effect.setInt(name, this._ints[name]);
  59485. }
  59486. // Float
  59487. for (name in this._floats) {
  59488. this._effect.setFloat(name, this._floats[name]);
  59489. }
  59490. // Floats
  59491. for (name in this._floatsArrays) {
  59492. this._effect.setArray(name, this._floatsArrays[name]);
  59493. }
  59494. // Color3
  59495. for (name in this._colors3) {
  59496. this._effect.setColor3(name, this._colors3[name]);
  59497. }
  59498. for (name in this._colors3Arrays) {
  59499. this._effect.setArray3(name, this._colors3Arrays[name]);
  59500. }
  59501. // Color4
  59502. for (name in this._colors4) {
  59503. var color = this._colors4[name];
  59504. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59505. }
  59506. // Vector2
  59507. for (name in this._vectors2) {
  59508. this._effect.setVector2(name, this._vectors2[name]);
  59509. }
  59510. // Vector3
  59511. for (name in this._vectors3) {
  59512. this._effect.setVector3(name, this._vectors3[name]);
  59513. }
  59514. // Vector4
  59515. for (name in this._vectors4) {
  59516. this._effect.setVector4(name, this._vectors4[name]);
  59517. }
  59518. // Matrix
  59519. for (name in this._matrices) {
  59520. this._effect.setMatrix(name, this._matrices[name]);
  59521. }
  59522. // Matrix 3x3
  59523. for (name in this._matrices3x3) {
  59524. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59525. }
  59526. // Matrix 2x2
  59527. for (name in this._matrices2x2) {
  59528. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59529. }
  59530. // Vector2Array
  59531. for (name in this._vectors2Arrays) {
  59532. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59533. }
  59534. // Vector3Array
  59535. for (name in this._vectors3Arrays) {
  59536. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59537. }
  59538. }
  59539. this._afterBind(mesh);
  59540. };
  59541. ShaderMaterial.prototype.getActiveTextures = function () {
  59542. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59543. for (var name in this._textures) {
  59544. activeTextures.push(this._textures[name]);
  59545. }
  59546. for (var name in this._textureArrays) {
  59547. var array = this._textureArrays[name];
  59548. for (var index = 0; index < array.length; index++) {
  59549. activeTextures.push(array[index]);
  59550. }
  59551. }
  59552. return activeTextures;
  59553. };
  59554. ShaderMaterial.prototype.hasTexture = function (texture) {
  59555. if (_super.prototype.hasTexture.call(this, texture)) {
  59556. return true;
  59557. }
  59558. for (var name in this._textures) {
  59559. if (this._textures[name] === texture) {
  59560. return true;
  59561. }
  59562. }
  59563. for (var name in this._textureArrays) {
  59564. var array = this._textureArrays[name];
  59565. for (var index = 0; index < array.length; index++) {
  59566. if (array[index] === texture) {
  59567. return true;
  59568. }
  59569. }
  59570. }
  59571. return false;
  59572. };
  59573. ShaderMaterial.prototype.clone = function (name) {
  59574. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59575. return newShaderMaterial;
  59576. };
  59577. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59578. if (forceDisposeTextures) {
  59579. var name;
  59580. for (name in this._textures) {
  59581. this._textures[name].dispose();
  59582. }
  59583. for (name in this._textureArrays) {
  59584. var array = this._textureArrays[name];
  59585. for (var index = 0; index < array.length; index++) {
  59586. array[index].dispose();
  59587. }
  59588. }
  59589. }
  59590. this._textures = {};
  59591. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59592. };
  59593. ShaderMaterial.prototype.serialize = function () {
  59594. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59595. serializationObject.customType = "BABYLON.ShaderMaterial";
  59596. serializationObject.options = this._options;
  59597. serializationObject.shaderPath = this._shaderPath;
  59598. var name;
  59599. // Texture
  59600. serializationObject.textures = {};
  59601. for (name in this._textures) {
  59602. serializationObject.textures[name] = this._textures[name].serialize();
  59603. }
  59604. // Texture arrays
  59605. serializationObject.textureArrays = {};
  59606. for (name in this._textureArrays) {
  59607. serializationObject.textureArrays[name] = [];
  59608. var array = this._textureArrays[name];
  59609. for (var index = 0; index < array.length; index++) {
  59610. serializationObject.textureArrays[name].push(array[index].serialize());
  59611. }
  59612. }
  59613. // Float
  59614. serializationObject.floats = {};
  59615. for (name in this._floats) {
  59616. serializationObject.floats[name] = this._floats[name];
  59617. }
  59618. // Float s
  59619. serializationObject.FloatArrays = {};
  59620. for (name in this._floatsArrays) {
  59621. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59622. }
  59623. // Color3
  59624. serializationObject.colors3 = {};
  59625. for (name in this._colors3) {
  59626. serializationObject.colors3[name] = this._colors3[name].asArray();
  59627. }
  59628. // Color3 array
  59629. serializationObject.colors3Arrays = {};
  59630. for (name in this._colors3Arrays) {
  59631. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59632. }
  59633. // Color4
  59634. serializationObject.colors4 = {};
  59635. for (name in this._colors4) {
  59636. serializationObject.colors4[name] = this._colors4[name].asArray();
  59637. }
  59638. // Vector2
  59639. serializationObject.vectors2 = {};
  59640. for (name in this._vectors2) {
  59641. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59642. }
  59643. // Vector3
  59644. serializationObject.vectors3 = {};
  59645. for (name in this._vectors3) {
  59646. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59647. }
  59648. // Vector4
  59649. serializationObject.vectors4 = {};
  59650. for (name in this._vectors4) {
  59651. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59652. }
  59653. // Matrix
  59654. serializationObject.matrices = {};
  59655. for (name in this._matrices) {
  59656. serializationObject.matrices[name] = this._matrices[name].asArray();
  59657. }
  59658. // Matrix 3x3
  59659. serializationObject.matrices3x3 = {};
  59660. for (name in this._matrices3x3) {
  59661. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59662. }
  59663. // Matrix 2x2
  59664. serializationObject.matrices2x2 = {};
  59665. for (name in this._matrices2x2) {
  59666. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59667. }
  59668. // Vector2Array
  59669. serializationObject.vectors2Arrays = {};
  59670. for (name in this._vectors2Arrays) {
  59671. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59672. }
  59673. // Vector3Array
  59674. serializationObject.vectors3Arrays = {};
  59675. for (name in this._vectors3Arrays) {
  59676. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59677. }
  59678. return serializationObject;
  59679. };
  59680. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59681. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59682. var name;
  59683. // Texture
  59684. for (name in source.textures) {
  59685. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59686. }
  59687. // Texture arrays
  59688. for (name in source.textureArrays) {
  59689. var array = source.textureArrays[name];
  59690. var textureArray = new Array();
  59691. for (var index = 0; index < array.length; index++) {
  59692. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59693. }
  59694. material.setTextureArray(name, textureArray);
  59695. }
  59696. // Float
  59697. for (name in source.floats) {
  59698. material.setFloat(name, source.floats[name]);
  59699. }
  59700. // Float s
  59701. for (name in source.floatsArrays) {
  59702. material.setFloats(name, source.floatsArrays[name]);
  59703. }
  59704. // Color3
  59705. for (name in source.colors3) {
  59706. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59707. }
  59708. // Color3 arrays
  59709. for (name in source.colors3Arrays) {
  59710. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59711. if (i % 3 === 0) {
  59712. arr.push([num]);
  59713. }
  59714. else {
  59715. arr[arr.length - 1].push(num);
  59716. }
  59717. return arr;
  59718. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59719. material.setColor3Array(name, colors);
  59720. }
  59721. // Color4
  59722. for (name in source.colors4) {
  59723. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59724. }
  59725. // Vector2
  59726. for (name in source.vectors2) {
  59727. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59728. }
  59729. // Vector3
  59730. for (name in source.vectors3) {
  59731. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59732. }
  59733. // Vector4
  59734. for (name in source.vectors4) {
  59735. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59736. }
  59737. // Matrix
  59738. for (name in source.matrices) {
  59739. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59740. }
  59741. // Matrix 3x3
  59742. for (name in source.matrices3x3) {
  59743. material.setMatrix3x3(name, source.matrices3x3[name]);
  59744. }
  59745. // Matrix 2x2
  59746. for (name in source.matrices2x2) {
  59747. material.setMatrix2x2(name, source.matrices2x2[name]);
  59748. }
  59749. // Vector2Array
  59750. for (name in source.vectors2Arrays) {
  59751. material.setArray2(name, source.vectors2Arrays[name]);
  59752. }
  59753. // Vector3Array
  59754. for (name in source.vectors3Arrays) {
  59755. material.setArray3(name, source.vectors3Arrays[name]);
  59756. }
  59757. return material;
  59758. };
  59759. return ShaderMaterial;
  59760. }(BABYLON.Material));
  59761. BABYLON.ShaderMaterial = ShaderMaterial;
  59762. })(BABYLON || (BABYLON = {}));
  59763. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59764. var BABYLON;
  59765. (function (BABYLON) {
  59766. var GroundMesh = /** @class */ (function (_super) {
  59767. __extends(GroundMesh, _super);
  59768. function GroundMesh(name, scene) {
  59769. var _this = _super.call(this, name, scene) || this;
  59770. _this.generateOctree = false;
  59771. return _this;
  59772. }
  59773. GroundMesh.prototype.getClassName = function () {
  59774. return "GroundMesh";
  59775. };
  59776. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59777. get: function () {
  59778. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59779. },
  59780. enumerable: true,
  59781. configurable: true
  59782. });
  59783. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59784. get: function () {
  59785. return this._subdivisionsX;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59791. get: function () {
  59792. return this._subdivisionsY;
  59793. },
  59794. enumerable: true,
  59795. configurable: true
  59796. });
  59797. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59798. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59799. this._subdivisionsX = chunksCount;
  59800. this._subdivisionsY = chunksCount;
  59801. this.subdivide(chunksCount);
  59802. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59803. };
  59804. /**
  59805. * Returns a height (y) value in the Worl system :
  59806. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59807. * Returns the ground y position if (x, z) are outside the ground surface.
  59808. */
  59809. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59810. var world = this.getWorldMatrix();
  59811. var invMat = BABYLON.Tmp.Matrix[5];
  59812. world.invertToRef(invMat);
  59813. var tmpVect = BABYLON.Tmp.Vector3[8];
  59814. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59815. x = tmpVect.x;
  59816. z = tmpVect.z;
  59817. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59818. return this.position.y;
  59819. }
  59820. if (!this._heightQuads || this._heightQuads.length == 0) {
  59821. this._initHeightQuads();
  59822. this._computeHeightQuads();
  59823. }
  59824. var facet = this._getFacetAt(x, z);
  59825. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59826. // return y in the World system
  59827. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59828. return tmpVect.y;
  59829. };
  59830. /**
  59831. * Returns a normalized vector (Vector3) orthogonal to the ground
  59832. * at the ground coordinates (x, z) expressed in the World system.
  59833. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59834. */
  59835. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59836. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59837. this.getNormalAtCoordinatesToRef(x, z, normal);
  59838. return normal;
  59839. };
  59840. /**
  59841. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59842. * at the ground coordinates (x, z) expressed in the World system.
  59843. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59844. * Returns the GroundMesh.
  59845. */
  59846. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59847. var world = this.getWorldMatrix();
  59848. var tmpMat = BABYLON.Tmp.Matrix[5];
  59849. world.invertToRef(tmpMat);
  59850. var tmpVect = BABYLON.Tmp.Vector3[8];
  59851. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59852. x = tmpVect.x;
  59853. z = tmpVect.z;
  59854. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59855. return this;
  59856. }
  59857. if (!this._heightQuads || this._heightQuads.length == 0) {
  59858. this._initHeightQuads();
  59859. this._computeHeightQuads();
  59860. }
  59861. var facet = this._getFacetAt(x, z);
  59862. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59863. return this;
  59864. };
  59865. /**
  59866. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59867. * if the ground has been updated.
  59868. * This can be used in the render loop.
  59869. * Returns the GroundMesh.
  59870. */
  59871. GroundMesh.prototype.updateCoordinateHeights = function () {
  59872. if (!this._heightQuads || this._heightQuads.length == 0) {
  59873. this._initHeightQuads();
  59874. }
  59875. this._computeHeightQuads();
  59876. return this;
  59877. };
  59878. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59879. GroundMesh.prototype._getFacetAt = function (x, z) {
  59880. // retrieve col and row from x, z coordinates in the ground local system
  59881. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59882. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59883. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59884. var facet;
  59885. if (z < quad.slope.x * x + quad.slope.y) {
  59886. facet = quad.facet1;
  59887. }
  59888. else {
  59889. facet = quad.facet2;
  59890. }
  59891. return facet;
  59892. };
  59893. // Creates and populates the heightMap array with "facet" elements :
  59894. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59895. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59896. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59897. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59898. // Returns the GroundMesh.
  59899. GroundMesh.prototype._initHeightQuads = function () {
  59900. var subdivisionsX = this._subdivisionsX;
  59901. var subdivisionsY = this._subdivisionsY;
  59902. this._heightQuads = new Array();
  59903. for (var row = 0; row < subdivisionsY; row++) {
  59904. for (var col = 0; col < subdivisionsX; col++) {
  59905. 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) };
  59906. this._heightQuads[row * subdivisionsX + col] = quad;
  59907. }
  59908. }
  59909. return this;
  59910. };
  59911. // Compute each quad element values and update the the heightMap array :
  59912. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59913. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59914. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59915. // Returns the GroundMesh.
  59916. GroundMesh.prototype._computeHeightQuads = function () {
  59917. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59918. if (!positions) {
  59919. return this;
  59920. }
  59921. var v1 = BABYLON.Tmp.Vector3[3];
  59922. var v2 = BABYLON.Tmp.Vector3[2];
  59923. var v3 = BABYLON.Tmp.Vector3[1];
  59924. var v4 = BABYLON.Tmp.Vector3[0];
  59925. var v1v2 = BABYLON.Tmp.Vector3[4];
  59926. var v1v3 = BABYLON.Tmp.Vector3[5];
  59927. var v1v4 = BABYLON.Tmp.Vector3[6];
  59928. var norm1 = BABYLON.Tmp.Vector3[7];
  59929. var norm2 = BABYLON.Tmp.Vector3[8];
  59930. var i = 0;
  59931. var j = 0;
  59932. var k = 0;
  59933. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59934. var h = 0;
  59935. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59936. var d2 = 0;
  59937. var subdivisionsX = this._subdivisionsX;
  59938. var subdivisionsY = this._subdivisionsY;
  59939. for (var row = 0; row < subdivisionsY; row++) {
  59940. for (var col = 0; col < subdivisionsX; col++) {
  59941. i = col * 3;
  59942. j = row * (subdivisionsX + 1) * 3;
  59943. k = (row + 1) * (subdivisionsX + 1) * 3;
  59944. v1.x = positions[j + i];
  59945. v1.y = positions[j + i + 1];
  59946. v1.z = positions[j + i + 2];
  59947. v2.x = positions[j + i + 3];
  59948. v2.y = positions[j + i + 4];
  59949. v2.z = positions[j + i + 5];
  59950. v3.x = positions[k + i];
  59951. v3.y = positions[k + i + 1];
  59952. v3.z = positions[k + i + 2];
  59953. v4.x = positions[k + i + 3];
  59954. v4.y = positions[k + i + 4];
  59955. v4.z = positions[k + i + 5];
  59956. // 2D slope V1V4
  59957. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59958. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59959. // facet equations :
  59960. // we compute each facet normal vector
  59961. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59962. // we compute the value d by applying the equation to v1 which belongs to the plane
  59963. // then we store the facet equation in a Vector4
  59964. v2.subtractToRef(v1, v1v2);
  59965. v3.subtractToRef(v1, v1v3);
  59966. v4.subtractToRef(v1, v1v4);
  59967. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59968. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59969. norm1.normalize();
  59970. norm2.normalize();
  59971. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59972. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59973. var quad = this._heightQuads[row * subdivisionsX + col];
  59974. quad.slope.copyFromFloats(cd, h);
  59975. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59976. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59977. }
  59978. }
  59979. return this;
  59980. };
  59981. GroundMesh.prototype.serialize = function (serializationObject) {
  59982. _super.prototype.serialize.call(this, serializationObject);
  59983. serializationObject.subdivisionsX = this._subdivisionsX;
  59984. serializationObject.subdivisionsY = this._subdivisionsY;
  59985. serializationObject.minX = this._minX;
  59986. serializationObject.maxX = this._maxX;
  59987. serializationObject.minZ = this._minZ;
  59988. serializationObject.maxZ = this._maxZ;
  59989. serializationObject.width = this._width;
  59990. serializationObject.height = this._height;
  59991. };
  59992. GroundMesh.Parse = function (parsedMesh, scene) {
  59993. var result = new GroundMesh(parsedMesh.name, scene);
  59994. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59995. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59996. result._minX = parsedMesh.minX;
  59997. result._maxX = parsedMesh.maxX;
  59998. result._minZ = parsedMesh.minZ;
  59999. result._maxZ = parsedMesh.maxZ;
  60000. result._width = parsedMesh.width;
  60001. result._height = parsedMesh.height;
  60002. return result;
  60003. };
  60004. return GroundMesh;
  60005. }(BABYLON.Mesh));
  60006. BABYLON.GroundMesh = GroundMesh;
  60007. })(BABYLON || (BABYLON = {}));
  60008. //# sourceMappingURL=babylon.groundMesh.js.map
  60009. var BABYLON;
  60010. (function (BABYLON) {
  60011. /**
  60012. * Creates an instance based on a source mesh.
  60013. */
  60014. var InstancedMesh = /** @class */ (function (_super) {
  60015. __extends(InstancedMesh, _super);
  60016. function InstancedMesh(name, source) {
  60017. var _this = _super.call(this, name, source.getScene()) || this;
  60018. source.instances.push(_this);
  60019. _this._sourceMesh = source;
  60020. _this.position.copyFrom(source.position);
  60021. _this.rotation.copyFrom(source.rotation);
  60022. _this.scaling.copyFrom(source.scaling);
  60023. if (source.rotationQuaternion) {
  60024. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60025. }
  60026. _this.infiniteDistance = source.infiniteDistance;
  60027. _this.setPivotMatrix(source.getPivotMatrix());
  60028. _this.refreshBoundingInfo();
  60029. _this._syncSubMeshes();
  60030. return _this;
  60031. }
  60032. /**
  60033. * Returns the string "InstancedMesh".
  60034. */
  60035. InstancedMesh.prototype.getClassName = function () {
  60036. return "InstancedMesh";
  60037. };
  60038. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60039. // Methods
  60040. get: function () {
  60041. return this._sourceMesh.receiveShadows;
  60042. },
  60043. enumerable: true,
  60044. configurable: true
  60045. });
  60046. Object.defineProperty(InstancedMesh.prototype, "material", {
  60047. get: function () {
  60048. return this._sourceMesh.material;
  60049. },
  60050. enumerable: true,
  60051. configurable: true
  60052. });
  60053. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60054. get: function () {
  60055. return this._sourceMesh.visibility;
  60056. },
  60057. enumerable: true,
  60058. configurable: true
  60059. });
  60060. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60061. get: function () {
  60062. return this._sourceMesh.skeleton;
  60063. },
  60064. enumerable: true,
  60065. configurable: true
  60066. });
  60067. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60068. get: function () {
  60069. return this._sourceMesh.renderingGroupId;
  60070. },
  60071. set: function (value) {
  60072. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60073. return;
  60074. }
  60075. //no-op with warning
  60076. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60077. },
  60078. enumerable: true,
  60079. configurable: true
  60080. });
  60081. /**
  60082. * Returns the total number of vertices (integer).
  60083. */
  60084. InstancedMesh.prototype.getTotalVertices = function () {
  60085. return this._sourceMesh.getTotalVertices();
  60086. };
  60087. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60088. get: function () {
  60089. return this._sourceMesh;
  60090. },
  60091. enumerable: true,
  60092. configurable: true
  60093. });
  60094. /**
  60095. * Is this node ready to be used/rendered
  60096. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60097. * @return {boolean} is it ready
  60098. */
  60099. InstancedMesh.prototype.isReady = function (completeCheck) {
  60100. if (completeCheck === void 0) { completeCheck = false; }
  60101. return this._sourceMesh.isReady(completeCheck, true);
  60102. };
  60103. /**
  60104. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60105. */
  60106. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60107. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60108. };
  60109. /**
  60110. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60111. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60112. * The `data` are either a numeric array either a Float32Array.
  60113. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60114. * 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).
  60115. * Note that a new underlying VertexBuffer object is created each call.
  60116. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60117. *
  60118. * Possible `kind` values :
  60119. * - BABYLON.VertexBuffer.PositionKind
  60120. * - BABYLON.VertexBuffer.UVKind
  60121. * - BABYLON.VertexBuffer.UV2Kind
  60122. * - BABYLON.VertexBuffer.UV3Kind
  60123. * - BABYLON.VertexBuffer.UV4Kind
  60124. * - BABYLON.VertexBuffer.UV5Kind
  60125. * - BABYLON.VertexBuffer.UV6Kind
  60126. * - BABYLON.VertexBuffer.ColorKind
  60127. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60128. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60129. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60130. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60131. *
  60132. * Returns the Mesh.
  60133. */
  60134. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60135. if (this.sourceMesh) {
  60136. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60137. }
  60138. return this.sourceMesh;
  60139. };
  60140. /**
  60141. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60142. * If the mesh has no geometry, it is simply returned as it is.
  60143. * The `data` are either a numeric array either a Float32Array.
  60144. * No new underlying VertexBuffer object is created.
  60145. * 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.
  60146. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60147. *
  60148. * Possible `kind` values :
  60149. * - BABYLON.VertexBuffer.PositionKind
  60150. * - BABYLON.VertexBuffer.UVKind
  60151. * - BABYLON.VertexBuffer.UV2Kind
  60152. * - BABYLON.VertexBuffer.UV3Kind
  60153. * - BABYLON.VertexBuffer.UV4Kind
  60154. * - BABYLON.VertexBuffer.UV5Kind
  60155. * - BABYLON.VertexBuffer.UV6Kind
  60156. * - BABYLON.VertexBuffer.ColorKind
  60157. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60158. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60159. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60160. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60161. *
  60162. * Returns the Mesh.
  60163. */
  60164. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60165. if (this.sourceMesh) {
  60166. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60167. }
  60168. return this.sourceMesh;
  60169. };
  60170. /**
  60171. * Sets the mesh indices.
  60172. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60173. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60174. * This method creates a new index buffer each call.
  60175. * Returns the Mesh.
  60176. */
  60177. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60178. if (totalVertices === void 0) { totalVertices = null; }
  60179. if (this.sourceMesh) {
  60180. this.sourceMesh.setIndices(indices, totalVertices);
  60181. }
  60182. return this.sourceMesh;
  60183. };
  60184. /**
  60185. * Boolean : True if the mesh owns the requested kind of data.
  60186. */
  60187. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60188. return this._sourceMesh.isVerticesDataPresent(kind);
  60189. };
  60190. /**
  60191. * Returns an array of indices (IndicesArray).
  60192. */
  60193. InstancedMesh.prototype.getIndices = function () {
  60194. return this._sourceMesh.getIndices();
  60195. };
  60196. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60197. get: function () {
  60198. return this._sourceMesh._positions;
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. /**
  60204. * Sets a new updated BoundingInfo to the mesh.
  60205. * Returns the mesh.
  60206. */
  60207. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60208. var meshBB = this._sourceMesh.getBoundingInfo();
  60209. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60210. this._updateBoundingInfo();
  60211. return this;
  60212. };
  60213. InstancedMesh.prototype._preActivate = function () {
  60214. if (this._currentLOD) {
  60215. this._currentLOD._preActivate();
  60216. }
  60217. return this;
  60218. };
  60219. InstancedMesh.prototype._activate = function (renderId) {
  60220. if (this._currentLOD) {
  60221. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60222. }
  60223. return this;
  60224. };
  60225. /**
  60226. * Returns the current associated LOD AbstractMesh.
  60227. */
  60228. InstancedMesh.prototype.getLOD = function (camera) {
  60229. if (!camera) {
  60230. return this;
  60231. }
  60232. var boundingInfo = this.getBoundingInfo();
  60233. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60234. if (this._currentLOD === this.sourceMesh) {
  60235. return this;
  60236. }
  60237. return this._currentLOD;
  60238. };
  60239. InstancedMesh.prototype._syncSubMeshes = function () {
  60240. this.releaseSubMeshes();
  60241. if (this._sourceMesh.subMeshes) {
  60242. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60243. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60244. }
  60245. }
  60246. return this;
  60247. };
  60248. InstancedMesh.prototype._generatePointsArray = function () {
  60249. return this._sourceMesh._generatePointsArray();
  60250. };
  60251. /**
  60252. * Creates a new InstancedMesh from the current mesh.
  60253. * - name (string) : the cloned mesh name
  60254. * - newParent (optional Node) : the optional Node to parent the clone to.
  60255. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60256. *
  60257. * Returns the clone.
  60258. */
  60259. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60260. var result = this._sourceMesh.createInstance(name);
  60261. // Deep copy
  60262. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60263. // Bounding info
  60264. this.refreshBoundingInfo();
  60265. // Parent
  60266. if (newParent) {
  60267. result.parent = newParent;
  60268. }
  60269. if (!doNotCloneChildren) {
  60270. // Children
  60271. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60272. var mesh = this.getScene().meshes[index];
  60273. if (mesh.parent === this) {
  60274. mesh.clone(mesh.name, result);
  60275. }
  60276. }
  60277. }
  60278. result.computeWorldMatrix(true);
  60279. return result;
  60280. };
  60281. /**
  60282. * Disposes the InstancedMesh.
  60283. * Returns nothing.
  60284. */
  60285. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60286. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60287. // Remove from mesh
  60288. var index = this._sourceMesh.instances.indexOf(this);
  60289. this._sourceMesh.instances.splice(index, 1);
  60290. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60291. };
  60292. return InstancedMesh;
  60293. }(BABYLON.AbstractMesh));
  60294. BABYLON.InstancedMesh = InstancedMesh;
  60295. })(BABYLON || (BABYLON = {}));
  60296. //# sourceMappingURL=babylon.instancedMesh.js.map
  60297. var BABYLON;
  60298. (function (BABYLON) {
  60299. var LinesMesh = /** @class */ (function (_super) {
  60300. __extends(LinesMesh, _super);
  60301. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60302. if (scene === void 0) { scene = null; }
  60303. if (parent === void 0) { parent = null; }
  60304. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60305. _this.useVertexColor = useVertexColor;
  60306. _this.useVertexAlpha = useVertexAlpha;
  60307. _this.color = new BABYLON.Color3(1, 1, 1);
  60308. _this.alpha = 1;
  60309. if (source) {
  60310. _this.color = source.color.clone();
  60311. _this.alpha = source.alpha;
  60312. _this.useVertexColor = source.useVertexColor;
  60313. _this.useVertexAlpha = source.useVertexAlpha;
  60314. }
  60315. _this._intersectionThreshold = 0.1;
  60316. var defines = [];
  60317. var options = {
  60318. attributes: [BABYLON.VertexBuffer.PositionKind],
  60319. uniforms: ["world", "viewProjection"],
  60320. needAlphaBlending: true,
  60321. defines: defines
  60322. };
  60323. if (useVertexAlpha === false) {
  60324. options.needAlphaBlending = false;
  60325. }
  60326. if (!useVertexColor) {
  60327. options.uniforms.push("color");
  60328. }
  60329. else {
  60330. options.defines.push("#define VERTEXCOLOR");
  60331. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60332. }
  60333. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60334. return _this;
  60335. }
  60336. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60337. /**
  60338. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60339. * This margin is expressed in world space coordinates, so its value may vary.
  60340. * Default value is 0.1
  60341. * @returns the intersection Threshold value.
  60342. */
  60343. get: function () {
  60344. return this._intersectionThreshold;
  60345. },
  60346. /**
  60347. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60348. * This margin is expressed in world space coordinates, so its value may vary.
  60349. * @param value the new threshold to apply
  60350. */
  60351. set: function (value) {
  60352. if (this._intersectionThreshold === value) {
  60353. return;
  60354. }
  60355. this._intersectionThreshold = value;
  60356. if (this.geometry) {
  60357. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60358. }
  60359. },
  60360. enumerable: true,
  60361. configurable: true
  60362. });
  60363. /**
  60364. * Returns the string "LineMesh"
  60365. */
  60366. LinesMesh.prototype.getClassName = function () {
  60367. return "LinesMesh";
  60368. };
  60369. Object.defineProperty(LinesMesh.prototype, "material", {
  60370. get: function () {
  60371. return this._colorShader;
  60372. },
  60373. set: function (value) {
  60374. // Do nothing
  60375. },
  60376. enumerable: true,
  60377. configurable: true
  60378. });
  60379. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60380. get: function () {
  60381. return false;
  60382. },
  60383. enumerable: true,
  60384. configurable: true
  60385. });
  60386. LinesMesh.prototype.createInstance = function (name) {
  60387. throw new Error("LinesMeshes do not support createInstance.");
  60388. };
  60389. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60390. if (!this._geometry) {
  60391. return this;
  60392. }
  60393. // VBOs
  60394. this._geometry._bind(this._colorShader.getEffect());
  60395. // Color
  60396. if (!this.useVertexColor) {
  60397. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60398. }
  60399. return this;
  60400. };
  60401. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60402. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60403. return this;
  60404. }
  60405. var engine = this.getScene().getEngine();
  60406. // Draw order
  60407. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60408. return this;
  60409. };
  60410. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60411. this._colorShader.dispose();
  60412. _super.prototype.dispose.call(this, doNotRecurse);
  60413. };
  60414. /**
  60415. * Returns a new LineMesh object cloned from the current one.
  60416. */
  60417. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60418. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60419. };
  60420. return LinesMesh;
  60421. }(BABYLON.Mesh));
  60422. BABYLON.LinesMesh = LinesMesh;
  60423. })(BABYLON || (BABYLON = {}));
  60424. //# sourceMappingURL=babylon.linesMesh.js.map
  60425. var BABYLON;
  60426. (function (BABYLON) {
  60427. /**
  60428. * Class containing static functions to help procedurally build meshes
  60429. */
  60430. var MeshBuilder = /** @class */ (function () {
  60431. function MeshBuilder() {
  60432. }
  60433. MeshBuilder.updateSideOrientation = function (orientation) {
  60434. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60435. return BABYLON.Mesh.DOUBLESIDE;
  60436. }
  60437. if (orientation === undefined || orientation === null) {
  60438. return BABYLON.Mesh.FRONTSIDE;
  60439. }
  60440. return orientation;
  60441. };
  60442. /**
  60443. * Creates a box mesh
  60444. * * The parameter `size` sets the size (float) of each box side (default 1)
  60445. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60446. * * 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)
  60447. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60448. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60449. * * 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
  60450. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60451. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60452. * @param name defines the name of the mesh
  60453. * @param options defines the options used to create the mesh
  60454. * @param scene defines the hosting scene
  60455. * @returns the box mesh
  60456. */
  60457. MeshBuilder.CreateBox = function (name, options, scene) {
  60458. if (scene === void 0) { scene = null; }
  60459. var box = new BABYLON.Mesh(name, scene);
  60460. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60461. box._originalBuilderSideOrientation = options.sideOrientation;
  60462. var vertexData = BABYLON.VertexData.CreateBox(options);
  60463. vertexData.applyToMesh(box, options.updatable);
  60464. return box;
  60465. };
  60466. /**
  60467. * Creates a sphere mesh
  60468. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60469. * * 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`)
  60470. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60471. * * 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
  60472. * * 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)
  60473. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60474. * * 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
  60475. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60476. * @param name defines the name of the mesh
  60477. * @param options defines the options used to create the mesh
  60478. * @param scene defines the hosting scene
  60479. * @returns the sphere mesh
  60480. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60481. */
  60482. MeshBuilder.CreateSphere = function (name, options, scene) {
  60483. var sphere = new BABYLON.Mesh(name, scene);
  60484. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60485. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60486. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60487. vertexData.applyToMesh(sphere, options.updatable);
  60488. return sphere;
  60489. };
  60490. /**
  60491. * Creates a plane polygonal mesh. By default, this is a disc
  60492. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60493. * * 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
  60494. * * 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
  60495. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60496. * * 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
  60497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60498. * @param name defines the name of the mesh
  60499. * @param options defines the options used to create the mesh
  60500. * @param scene defines the hosting scene
  60501. * @returns the plane polygonal mesh
  60502. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60503. */
  60504. MeshBuilder.CreateDisc = function (name, options, scene) {
  60505. if (scene === void 0) { scene = null; }
  60506. var disc = new BABYLON.Mesh(name, scene);
  60507. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60508. disc._originalBuilderSideOrientation = options.sideOrientation;
  60509. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60510. vertexData.applyToMesh(disc, options.updatable);
  60511. return disc;
  60512. };
  60513. /**
  60514. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60515. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60516. * * 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`)
  60517. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60518. * * 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
  60519. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60520. * * 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
  60521. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60522. * @param name defines the name of the mesh
  60523. * @param options defines the options used to create the mesh
  60524. * @param scene defines the hosting scene
  60525. * @returns the icosahedron mesh
  60526. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60527. */
  60528. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60529. var sphere = new BABYLON.Mesh(name, scene);
  60530. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60531. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60532. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60533. vertexData.applyToMesh(sphere, options.updatable);
  60534. return sphere;
  60535. };
  60536. ;
  60537. /**
  60538. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60539. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60540. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60541. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60542. * * 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
  60543. * * 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
  60544. * * 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
  60545. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60546. * * 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
  60547. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60548. * * 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
  60549. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60550. * * 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
  60551. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60552. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60553. * @param name defines the name of the mesh
  60554. * @param options defines the options used to create the mesh
  60555. * @param scene defines the hosting scene
  60556. * @returns the ribbon mesh
  60557. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60558. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60559. */
  60560. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60561. if (scene === void 0) { scene = null; }
  60562. var pathArray = options.pathArray;
  60563. var closeArray = options.closeArray;
  60564. var closePath = options.closePath;
  60565. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60566. var instance = options.instance;
  60567. var updatable = options.updatable;
  60568. if (instance) { // existing ribbon instance update
  60569. // positionFunction : ribbon case
  60570. // only pathArray and sideOrientation parameters are taken into account for positions update
  60571. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60572. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60573. var positionFunction = function (positions) {
  60574. var minlg = pathArray[0].length;
  60575. var i = 0;
  60576. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60577. for (var si = 1; si <= ns; si++) {
  60578. for (var p = 0; p < pathArray.length; p++) {
  60579. var path = pathArray[p];
  60580. var l = path.length;
  60581. minlg = (minlg < l) ? minlg : l;
  60582. var j = 0;
  60583. while (j < minlg) {
  60584. positions[i] = path[j].x;
  60585. positions[i + 1] = path[j].y;
  60586. positions[i + 2] = path[j].z;
  60587. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60588. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60589. }
  60590. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60591. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60592. }
  60593. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60594. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60595. }
  60596. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60597. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60598. }
  60599. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60600. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60601. }
  60602. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60603. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60604. }
  60605. j++;
  60606. i += 3;
  60607. }
  60608. if (instance._closePath) {
  60609. positions[i] = path[0].x;
  60610. positions[i + 1] = path[0].y;
  60611. positions[i + 2] = path[0].z;
  60612. i += 3;
  60613. }
  60614. }
  60615. }
  60616. };
  60617. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60618. positionFunction(positions);
  60619. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60620. instance._boundingInfo.update(instance._worldMatrix);
  60621. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60622. if (options.colors) {
  60623. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60624. for (var c = 0; c < options.colors.length; c++) {
  60625. colors[c * 4] = options.colors[c].r;
  60626. colors[c * 4 + 1] = options.colors[c].g;
  60627. colors[c * 4 + 2] = options.colors[c].b;
  60628. colors[c * 4 + 3] = options.colors[c].a;
  60629. }
  60630. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60631. }
  60632. if (options.uvs) {
  60633. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60634. for (var i = 0; i < options.uvs.length; i++) {
  60635. uvs[i * 2] = options.uvs[i].x;
  60636. uvs[i * 2 + 1] = options.uvs[i].y;
  60637. }
  60638. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60639. }
  60640. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60641. var indices = instance.getIndices();
  60642. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60643. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60644. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60645. if (instance._closePath) {
  60646. var indexFirst = 0;
  60647. var indexLast = 0;
  60648. for (var p = 0; p < pathArray.length; p++) {
  60649. indexFirst = instance._idx[p] * 3;
  60650. if (p + 1 < pathArray.length) {
  60651. indexLast = (instance._idx[p + 1] - 1) * 3;
  60652. }
  60653. else {
  60654. indexLast = normals.length - 3;
  60655. }
  60656. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60657. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60658. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60659. normals[indexLast] = normals[indexFirst];
  60660. normals[indexLast + 1] = normals[indexFirst + 1];
  60661. normals[indexLast + 2] = normals[indexFirst + 2];
  60662. }
  60663. }
  60664. if (!(instance.areNormalsFrozen)) {
  60665. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60666. }
  60667. }
  60668. return instance;
  60669. }
  60670. else { // new ribbon creation
  60671. var ribbon = new BABYLON.Mesh(name, scene);
  60672. ribbon._originalBuilderSideOrientation = sideOrientation;
  60673. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60674. if (closePath) {
  60675. ribbon._idx = vertexData._idx;
  60676. }
  60677. ribbon._closePath = closePath;
  60678. ribbon._closeArray = closeArray;
  60679. vertexData.applyToMesh(ribbon, updatable);
  60680. return ribbon;
  60681. }
  60682. };
  60683. /**
  60684. * Creates a cylinder or a cone mesh
  60685. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60686. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60687. * * 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.
  60688. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60689. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60690. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60691. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60692. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60693. * * 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).
  60694. * * 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
  60695. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60696. * * 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
  60697. * * 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.
  60698. * * If `enclose` is false, a ring surface is one element.
  60699. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60700. * * 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
  60701. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60702. * * 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
  60703. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60704. * @param name defines the name of the mesh
  60705. * @param options defines the options used to create the mesh
  60706. * @param scene defines the hosting scene
  60707. * @returns the cylinder mesh
  60708. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60709. */
  60710. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60711. var cylinder = new BABYLON.Mesh(name, scene);
  60712. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60713. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60714. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60715. vertexData.applyToMesh(cylinder, options.updatable);
  60716. return cylinder;
  60717. };
  60718. /**
  60719. * Creates a torus mesh
  60720. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60721. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60722. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60723. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60724. * * 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
  60725. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60726. * @param name defines the name of the mesh
  60727. * @param options defines the options used to create the mesh
  60728. * @param scene defines the hosting scene
  60729. * @returns the torus mesh
  60730. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60731. */
  60732. MeshBuilder.CreateTorus = function (name, options, scene) {
  60733. var torus = new BABYLON.Mesh(name, scene);
  60734. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60735. torus._originalBuilderSideOrientation = options.sideOrientation;
  60736. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60737. vertexData.applyToMesh(torus, options.updatable);
  60738. return torus;
  60739. };
  60740. /**
  60741. * Creates a torus knot mesh
  60742. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60743. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60744. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60745. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60746. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60747. * * 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
  60748. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60749. * @param name defines the name of the mesh
  60750. * @param options defines the options used to create the mesh
  60751. * @param scene defines the hosting scene
  60752. * @returns the torus knot mesh
  60753. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60754. */
  60755. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60756. var torusKnot = new BABYLON.Mesh(name, scene);
  60757. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60758. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60759. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60760. vertexData.applyToMesh(torusKnot, options.updatable);
  60761. return torusKnot;
  60762. };
  60763. /**
  60764. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60765. * * 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
  60766. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60767. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60768. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60769. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60770. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60771. * * 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
  60772. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60773. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60774. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60775. * @param name defines the name of the new line system
  60776. * @param options defines the options used to create the line system
  60777. * @param scene defines the hosting scene
  60778. * @returns a new line system mesh
  60779. */
  60780. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60781. var instance = options.instance;
  60782. var lines = options.lines;
  60783. var colors = options.colors;
  60784. if (instance) { // lines update
  60785. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60786. var vertexColor;
  60787. var lineColors;
  60788. if (colors) {
  60789. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60790. }
  60791. var i = 0;
  60792. var c = 0;
  60793. for (var l = 0; l < lines.length; l++) {
  60794. var points = lines[l];
  60795. for (var p = 0; p < points.length; p++) {
  60796. positions[i] = points[p].x;
  60797. positions[i + 1] = points[p].y;
  60798. positions[i + 2] = points[p].z;
  60799. if (colors && vertexColor) {
  60800. lineColors = colors[l];
  60801. vertexColor[c] = lineColors[p].r;
  60802. vertexColor[c + 1] = lineColors[p].g;
  60803. vertexColor[c + 2] = lineColors[p].b;
  60804. vertexColor[c + 3] = lineColors[p].a;
  60805. c += 4;
  60806. }
  60807. i += 3;
  60808. }
  60809. }
  60810. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60811. if (colors && vertexColor) {
  60812. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60813. }
  60814. return instance;
  60815. }
  60816. // line system creation
  60817. var useVertexColor = (colors) ? true : false;
  60818. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60819. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60820. vertexData.applyToMesh(lineSystem, options.updatable);
  60821. return lineSystem;
  60822. };
  60823. /**
  60824. * Creates a line mesh
  60825. * 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
  60826. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60827. * * The parameter `points` is an array successive Vector3
  60828. * * 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
  60829. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60830. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60831. * * When updating an instance, remember that only point positions can change, not the number of points
  60832. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60833. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60834. * @param name defines the name of the new line system
  60835. * @param options defines the options used to create the line system
  60836. * @param scene defines the hosting scene
  60837. * @returns a new line mesh
  60838. */
  60839. MeshBuilder.CreateLines = function (name, options, scene) {
  60840. if (scene === void 0) { scene = null; }
  60841. var colors = (options.colors) ? [options.colors] : null;
  60842. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60843. return lines;
  60844. };
  60845. /**
  60846. * Creates a dashed line mesh
  60847. * * 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
  60848. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60849. * * The parameter `points` is an array successive Vector3
  60850. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60851. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60852. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60853. * * 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
  60854. * * When updating an instance, remember that only point positions can change, not the number of points
  60855. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60856. * @param name defines the name of the mesh
  60857. * @param options defines the options used to create the mesh
  60858. * @param scene defines the hosting scene
  60859. * @returns the dashed line mesh
  60860. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60861. */
  60862. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60863. if (scene === void 0) { scene = null; }
  60864. var points = options.points;
  60865. var instance = options.instance;
  60866. var gapSize = options.gapSize || 1;
  60867. var dashSize = options.dashSize || 3;
  60868. if (instance) { // dashed lines update
  60869. var positionFunction = function (positions) {
  60870. var curvect = BABYLON.Vector3.Zero();
  60871. var nbSeg = positions.length / 6;
  60872. var lg = 0;
  60873. var nb = 0;
  60874. var shft = 0;
  60875. var dashshft = 0;
  60876. var curshft = 0;
  60877. var p = 0;
  60878. var i = 0;
  60879. var j = 0;
  60880. for (i = 0; i < points.length - 1; i++) {
  60881. points[i + 1].subtractToRef(points[i], curvect);
  60882. lg += curvect.length();
  60883. }
  60884. shft = lg / nbSeg;
  60885. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60886. for (i = 0; i < points.length - 1; i++) {
  60887. points[i + 1].subtractToRef(points[i], curvect);
  60888. nb = Math.floor(curvect.length() / shft);
  60889. curvect.normalize();
  60890. j = 0;
  60891. while (j < nb && p < positions.length) {
  60892. curshft = shft * j;
  60893. positions[p] = points[i].x + curshft * curvect.x;
  60894. positions[p + 1] = points[i].y + curshft * curvect.y;
  60895. positions[p + 2] = points[i].z + curshft * curvect.z;
  60896. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60897. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60898. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60899. p += 6;
  60900. j++;
  60901. }
  60902. }
  60903. while (p < positions.length) {
  60904. positions[p] = points[i].x;
  60905. positions[p + 1] = points[i].y;
  60906. positions[p + 2] = points[i].z;
  60907. p += 3;
  60908. }
  60909. };
  60910. instance.updateMeshPositions(positionFunction, false);
  60911. return instance;
  60912. }
  60913. // dashed lines creation
  60914. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60915. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60916. vertexData.applyToMesh(dashedLines, options.updatable);
  60917. dashedLines.dashSize = dashSize;
  60918. dashedLines.gapSize = gapSize;
  60919. return dashedLines;
  60920. };
  60921. /**
  60922. * 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.
  60923. * * 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.
  60924. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60925. * * 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.
  60926. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60927. * * 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
  60928. * * 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
  60929. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60930. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60931. * * 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
  60932. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60933. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60934. * @param name defines the name of the mesh
  60935. * @param options defines the options used to create the mesh
  60936. * @param scene defines the hosting scene
  60937. * @returns the extruded shape mesh
  60938. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60939. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60940. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60941. */
  60942. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60943. if (scene === void 0) { scene = null; }
  60944. var path = options.path;
  60945. var shape = options.shape;
  60946. var scale = options.scale || 1;
  60947. var rotation = options.rotation || 0;
  60948. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60949. var updatable = options.updatable;
  60950. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60951. var instance = options.instance || null;
  60952. var invertUV = options.invertUV || false;
  60953. 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);
  60954. };
  60955. /**
  60956. * Creates an custom extruded shape mesh.
  60957. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60958. * * 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.
  60959. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60960. * * 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
  60961. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60962. * * 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
  60963. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60964. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60965. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60966. * * 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
  60967. * * 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
  60968. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60969. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60970. * * 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
  60971. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60972. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60973. * @param name defines the name of the mesh
  60974. * @param options defines the options used to create the mesh
  60975. * @param scene defines the hosting scene
  60976. * @returns the custom extruded shape mesh
  60977. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60978. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60979. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60980. */
  60981. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60982. var path = options.path;
  60983. var shape = options.shape;
  60984. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60985. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60986. var ribbonCloseArray = options.ribbonCloseArray || false;
  60987. var ribbonClosePath = options.ribbonClosePath || false;
  60988. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60989. var updatable = options.updatable;
  60990. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60991. var instance = options.instance;
  60992. var invertUV = options.invertUV || false;
  60993. 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);
  60994. };
  60995. /**
  60996. * Creates lathe mesh.
  60997. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60998. * * 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
  60999. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61000. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61001. * * 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
  61002. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61003. * * 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
  61004. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61005. * * 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
  61006. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  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 lathe mesh
  61012. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61013. */
  61014. MeshBuilder.CreateLathe = function (name, options, scene) {
  61015. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61016. var closed = (options.closed === undefined) ? true : options.closed;
  61017. var shape = options.shape;
  61018. var radius = options.radius || 1;
  61019. var tessellation = options.tessellation || 64;
  61020. var updatable = options.updatable;
  61021. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61022. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61023. var pi2 = Math.PI * 2;
  61024. var paths = new Array();
  61025. var invertUV = options.invertUV || false;
  61026. var i = 0;
  61027. var p = 0;
  61028. var step = pi2 / tessellation * arc;
  61029. var rotated;
  61030. var path = new Array();
  61031. for (i = 0; i <= tessellation; i++) {
  61032. var path = [];
  61033. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61034. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61035. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61036. }
  61037. for (p = 0; p < shape.length; p++) {
  61038. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61039. path.push(rotated);
  61040. }
  61041. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61042. 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));
  61043. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61044. }
  61045. paths.push(path);
  61046. }
  61047. // lathe ribbon
  61048. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61049. return lathe;
  61050. };
  61051. /**
  61052. * Creates a plane mesh
  61053. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61054. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61055. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61056. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61057. * * 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
  61058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61059. * @param name defines the name of the mesh
  61060. * @param options defines the options used to create the mesh
  61061. * @param scene defines the hosting scene
  61062. * @returns the plane mesh
  61063. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61064. */
  61065. MeshBuilder.CreatePlane = function (name, options, scene) {
  61066. var plane = new BABYLON.Mesh(name, scene);
  61067. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61068. plane._originalBuilderSideOrientation = options.sideOrientation;
  61069. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61070. vertexData.applyToMesh(plane, options.updatable);
  61071. if (options.sourcePlane) {
  61072. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61073. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61074. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61075. plane.rotate(vectorProduct, product);
  61076. }
  61077. return plane;
  61078. };
  61079. /**
  61080. * Creates a ground mesh
  61081. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61082. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61083. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61084. * @param name defines the name of the mesh
  61085. * @param options defines the options used to create the mesh
  61086. * @param scene defines the hosting scene
  61087. * @returns the ground mesh
  61088. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61089. */
  61090. MeshBuilder.CreateGround = function (name, options, scene) {
  61091. var ground = new BABYLON.GroundMesh(name, scene);
  61092. ground._setReady(false);
  61093. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61094. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61095. ground._width = options.width || 1;
  61096. ground._height = options.height || 1;
  61097. ground._maxX = ground._width / 2;
  61098. ground._maxZ = ground._height / 2;
  61099. ground._minX = -ground._maxX;
  61100. ground._minZ = -ground._maxZ;
  61101. var vertexData = BABYLON.VertexData.CreateGround(options);
  61102. vertexData.applyToMesh(ground, options.updatable);
  61103. ground._setReady(true);
  61104. return ground;
  61105. };
  61106. /**
  61107. * Creates a tiled ground mesh
  61108. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61109. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61110. * * 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
  61111. * * 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
  61112. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61113. * @param name defines the name of the mesh
  61114. * @param options defines the options used to create the mesh
  61115. * @param scene defines the hosting scene
  61116. * @returns the tiled ground mesh
  61117. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61118. */
  61119. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61120. var tiledGround = new BABYLON.Mesh(name, scene);
  61121. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61122. vertexData.applyToMesh(tiledGround, options.updatable);
  61123. return tiledGround;
  61124. };
  61125. /**
  61126. * Creates a ground mesh from a height map
  61127. * * The parameter `url` sets the URL of the height map image resource.
  61128. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61129. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61130. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61131. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61132. * * 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.
  61133. * * 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).
  61134. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61135. * @param name defines the name of the mesh
  61136. * @param url defines the url to the height map
  61137. * @param options defines the options used to create the mesh
  61138. * @param scene defines the hosting scene
  61139. * @returns the ground mesh
  61140. * @see http://doc.babylonjs.com/babylon101/height_map
  61141. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61142. */
  61143. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61144. var width = options.width || 10.0;
  61145. var height = options.height || 10.0;
  61146. var subdivisions = options.subdivisions || 1 | 0;
  61147. var minHeight = options.minHeight || 0.0;
  61148. var maxHeight = options.maxHeight || 1.0;
  61149. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61150. var updatable = options.updatable;
  61151. var onReady = options.onReady;
  61152. var ground = new BABYLON.GroundMesh(name, scene);
  61153. ground._subdivisionsX = subdivisions;
  61154. ground._subdivisionsY = subdivisions;
  61155. ground._width = width;
  61156. ground._height = height;
  61157. ground._maxX = ground._width / 2.0;
  61158. ground._maxZ = ground._height / 2.0;
  61159. ground._minX = -ground._maxX;
  61160. ground._minZ = -ground._maxZ;
  61161. ground._setReady(false);
  61162. var onload = function (img) {
  61163. // Getting height map data
  61164. var canvas = document.createElement("canvas");
  61165. var context = canvas.getContext("2d");
  61166. if (!context) {
  61167. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61168. }
  61169. if (scene.isDisposed) {
  61170. return;
  61171. }
  61172. var bufferWidth = img.width;
  61173. var bufferHeight = img.height;
  61174. canvas.width = bufferWidth;
  61175. canvas.height = bufferHeight;
  61176. context.drawImage(img, 0, 0);
  61177. // Create VertexData from map data
  61178. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61179. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61180. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61181. width: width, height: height,
  61182. subdivisions: subdivisions,
  61183. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61184. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61185. });
  61186. vertexData.applyToMesh(ground, updatable);
  61187. //execute ready callback, if set
  61188. if (onReady) {
  61189. onReady(ground);
  61190. }
  61191. ground._setReady(true);
  61192. };
  61193. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61194. return ground;
  61195. };
  61196. /**
  61197. * Creates a polygon mesh
  61198. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61199. * * 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
  61200. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61201. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61202. * * 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)
  61203. * * Remember you can only change the shape positions, not their number when updating a polygon
  61204. * @param name defines the name of the mesh
  61205. * @param options defines the options used to create the mesh
  61206. * @param scene defines the hosting scene
  61207. * @returns the polygon mesh
  61208. */
  61209. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61210. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61211. var shape = options.shape;
  61212. var holes = options.holes || [];
  61213. var depth = options.depth || 0;
  61214. var contours = [];
  61215. var hole = [];
  61216. for (var i = 0; i < shape.length; i++) {
  61217. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61218. }
  61219. var epsilon = 0.00000001;
  61220. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61221. contours.pop();
  61222. }
  61223. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61224. for (var hNb = 0; hNb < holes.length; hNb++) {
  61225. hole = [];
  61226. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61227. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61228. }
  61229. polygonTriangulation.addHole(hole);
  61230. }
  61231. var polygon = polygonTriangulation.build(options.updatable, depth);
  61232. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61233. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61234. vertexData.applyToMesh(polygon, options.updatable);
  61235. return polygon;
  61236. };
  61237. ;
  61238. /**
  61239. * Creates an extruded polygon mesh, with depth in the Y direction.
  61240. * * 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)
  61241. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61242. * @param name defines the name of the mesh
  61243. * @param options defines the options used to create the mesh
  61244. * @param scene defines the hosting scene
  61245. * @returns the polygon mesh
  61246. */
  61247. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61248. return MeshBuilder.CreatePolygon(name, options, scene);
  61249. };
  61250. ;
  61251. /**
  61252. * Creates a tube mesh.
  61253. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61254. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61255. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61256. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61257. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61258. * * 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)
  61259. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61260. * * 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
  61261. * * 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
  61262. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61263. * * 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
  61264. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61265. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61266. * @param name defines the name of the mesh
  61267. * @param options defines the options used to create the mesh
  61268. * @param scene defines the hosting scene
  61269. * @returns the tube mesh
  61270. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61271. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61272. */
  61273. MeshBuilder.CreateTube = function (name, options, scene) {
  61274. var path = options.path;
  61275. var instance = options.instance;
  61276. var radius = 1.0;
  61277. if (instance) {
  61278. radius = instance.radius;
  61279. }
  61280. if (options.radius !== undefined) {
  61281. radius = options.radius;
  61282. }
  61283. ;
  61284. var tessellation = options.tessellation || 64 | 0;
  61285. var radiusFunction = options.radiusFunction || null;
  61286. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61287. var invertUV = options.invertUV || false;
  61288. var updatable = options.updatable;
  61289. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61290. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61291. // tube geometry
  61292. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61293. var tangents = path3D.getTangents();
  61294. var normals = path3D.getNormals();
  61295. var distances = path3D.getDistances();
  61296. var pi2 = Math.PI * 2;
  61297. var step = pi2 / tessellation * arc;
  61298. var returnRadius = function () { return radius; };
  61299. var radiusFunctionFinal = radiusFunction || returnRadius;
  61300. var circlePath;
  61301. var rad;
  61302. var normal;
  61303. var rotated;
  61304. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61305. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61306. for (var i = 0; i < path.length; i++) {
  61307. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61308. circlePath = Array(); // current circle array
  61309. normal = normals[i]; // current normal
  61310. for (var t = 0; t < tessellation; t++) {
  61311. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61312. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61313. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61314. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61315. circlePath[t] = rotated;
  61316. }
  61317. circlePaths[index] = circlePath;
  61318. index++;
  61319. }
  61320. // cap
  61321. var capPath = function (nbPoints, pathIndex) {
  61322. var pointCap = Array();
  61323. for (var i = 0; i < nbPoints; i++) {
  61324. pointCap.push(path[pathIndex]);
  61325. }
  61326. return pointCap;
  61327. };
  61328. switch (cap) {
  61329. case BABYLON.Mesh.NO_CAP:
  61330. break;
  61331. case BABYLON.Mesh.CAP_START:
  61332. circlePaths[0] = capPath(tessellation, 0);
  61333. circlePaths[1] = circlePaths[2].slice(0);
  61334. break;
  61335. case BABYLON.Mesh.CAP_END:
  61336. circlePaths[index] = circlePaths[index - 1].slice(0);
  61337. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61338. break;
  61339. case BABYLON.Mesh.CAP_ALL:
  61340. circlePaths[0] = capPath(tessellation, 0);
  61341. circlePaths[1] = circlePaths[2].slice(0);
  61342. circlePaths[index] = circlePaths[index - 1].slice(0);
  61343. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61344. break;
  61345. default:
  61346. break;
  61347. }
  61348. return circlePaths;
  61349. };
  61350. var path3D;
  61351. var pathArray;
  61352. if (instance) { // tube update
  61353. var arc = options.arc || instance.arc;
  61354. path3D = (instance.path3D).update(path);
  61355. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61356. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61357. instance.path3D = path3D;
  61358. instance.pathArray = pathArray;
  61359. instance.arc = arc;
  61360. instance.radius = radius;
  61361. return instance;
  61362. }
  61363. // tube creation
  61364. path3D = new BABYLON.Path3D(path);
  61365. var newPathArray = new Array();
  61366. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61367. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61368. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61369. tube.pathArray = pathArray;
  61370. tube.path3D = path3D;
  61371. tube.tessellation = tessellation;
  61372. tube.cap = cap;
  61373. tube.arc = options.arc;
  61374. tube.radius = radius;
  61375. return tube;
  61376. };
  61377. /**
  61378. * Creates a polyhedron mesh
  61379. * * 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
  61380. * * The parameter `size` (positive float, default 1) sets the polygon size
  61381. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61382. * * 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`
  61383. * * 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
  61384. * * 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)`)
  61385. * * 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
  61386. * * 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
  61387. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61388. * * 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
  61389. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61390. * @param name defines the name of the mesh
  61391. * @param options defines the options used to create the mesh
  61392. * @param scene defines the hosting scene
  61393. * @returns the polyhedron mesh
  61394. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61395. */
  61396. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61397. var polyhedron = new BABYLON.Mesh(name, scene);
  61398. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61399. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61400. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61401. vertexData.applyToMesh(polyhedron, options.updatable);
  61402. return polyhedron;
  61403. };
  61404. /**
  61405. * Creates a decal mesh.
  61406. * 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
  61407. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61408. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61409. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61410. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61411. * @param name defines the name of the mesh
  61412. * @param sourceMesh defines the mesh where the decal must be applied
  61413. * @param options defines the options used to create the mesh
  61414. * @param scene defines the hosting scene
  61415. * @returns the decal mesh
  61416. * @see http://doc.babylonjs.com/how_to/decals
  61417. */
  61418. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61419. var indices = sourceMesh.getIndices();
  61420. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61421. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61422. var position = options.position || BABYLON.Vector3.Zero();
  61423. var normal = options.normal || BABYLON.Vector3.Up();
  61424. var size = options.size || BABYLON.Vector3.One();
  61425. var angle = options.angle || 0;
  61426. // Getting correct rotation
  61427. if (!normal) {
  61428. var target = new BABYLON.Vector3(0, 0, 1);
  61429. var camera = sourceMesh.getScene().activeCamera;
  61430. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61431. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61432. }
  61433. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61434. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61435. var pitch = Math.atan2(normal.y, len);
  61436. // Matrix
  61437. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61438. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61439. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61440. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61441. var vertexData = new BABYLON.VertexData();
  61442. vertexData.indices = [];
  61443. vertexData.positions = [];
  61444. vertexData.normals = [];
  61445. vertexData.uvs = [];
  61446. var currentVertexDataIndex = 0;
  61447. var extractDecalVector3 = function (indexId) {
  61448. var result = new BABYLON.PositionNormalVertex();
  61449. if (!indices || !positions || !normals) {
  61450. return result;
  61451. }
  61452. var vertexId = indices[indexId];
  61453. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61454. // Send vector to decal local world
  61455. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61456. // Get normal
  61457. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61458. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61459. return result;
  61460. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61461. var clip = function (vertices, axis) {
  61462. if (vertices.length === 0) {
  61463. return vertices;
  61464. }
  61465. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61466. var clipVertices = function (v0, v1) {
  61467. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61468. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61469. };
  61470. var result = new Array();
  61471. for (var index = 0; index < vertices.length; index += 3) {
  61472. var v1Out;
  61473. var v2Out;
  61474. var v3Out;
  61475. var total = 0;
  61476. var nV1 = null;
  61477. var nV2 = null;
  61478. var nV3 = null;
  61479. var nV4 = null;
  61480. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61481. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61482. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61483. v1Out = d1 > 0;
  61484. v2Out = d2 > 0;
  61485. v3Out = d3 > 0;
  61486. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61487. switch (total) {
  61488. case 0:
  61489. result.push(vertices[index]);
  61490. result.push(vertices[index + 1]);
  61491. result.push(vertices[index + 2]);
  61492. break;
  61493. case 1:
  61494. if (v1Out) {
  61495. nV1 = vertices[index + 1];
  61496. nV2 = vertices[index + 2];
  61497. nV3 = clipVertices(vertices[index], nV1);
  61498. nV4 = clipVertices(vertices[index], nV2);
  61499. }
  61500. if (v2Out) {
  61501. nV1 = vertices[index];
  61502. nV2 = vertices[index + 2];
  61503. nV3 = clipVertices(vertices[index + 1], nV1);
  61504. nV4 = clipVertices(vertices[index + 1], nV2);
  61505. result.push(nV3);
  61506. result.push(nV2.clone());
  61507. result.push(nV1.clone());
  61508. result.push(nV2.clone());
  61509. result.push(nV3.clone());
  61510. result.push(nV4);
  61511. break;
  61512. }
  61513. if (v3Out) {
  61514. nV1 = vertices[index];
  61515. nV2 = vertices[index + 1];
  61516. nV3 = clipVertices(vertices[index + 2], nV1);
  61517. nV4 = clipVertices(vertices[index + 2], nV2);
  61518. }
  61519. if (nV1 && nV2 && nV3 && nV4) {
  61520. result.push(nV1.clone());
  61521. result.push(nV2.clone());
  61522. result.push(nV3);
  61523. result.push(nV4);
  61524. result.push(nV3.clone());
  61525. result.push(nV2.clone());
  61526. }
  61527. break;
  61528. case 2:
  61529. if (!v1Out) {
  61530. nV1 = vertices[index].clone();
  61531. nV2 = clipVertices(nV1, vertices[index + 1]);
  61532. nV3 = clipVertices(nV1, vertices[index + 2]);
  61533. result.push(nV1);
  61534. result.push(nV2);
  61535. result.push(nV3);
  61536. }
  61537. if (!v2Out) {
  61538. nV1 = vertices[index + 1].clone();
  61539. nV2 = clipVertices(nV1, vertices[index + 2]);
  61540. nV3 = clipVertices(nV1, vertices[index]);
  61541. result.push(nV1);
  61542. result.push(nV2);
  61543. result.push(nV3);
  61544. }
  61545. if (!v3Out) {
  61546. nV1 = vertices[index + 2].clone();
  61547. nV2 = clipVertices(nV1, vertices[index]);
  61548. nV3 = clipVertices(nV1, vertices[index + 1]);
  61549. result.push(nV1);
  61550. result.push(nV2);
  61551. result.push(nV3);
  61552. }
  61553. break;
  61554. case 3:
  61555. break;
  61556. }
  61557. }
  61558. return result;
  61559. };
  61560. for (var index = 0; index < indices.length; index += 3) {
  61561. var faceVertices = new Array();
  61562. faceVertices.push(extractDecalVector3(index));
  61563. faceVertices.push(extractDecalVector3(index + 1));
  61564. faceVertices.push(extractDecalVector3(index + 2));
  61565. // Clip
  61566. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61567. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61568. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61569. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61570. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61571. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61572. if (faceVertices.length === 0) {
  61573. continue;
  61574. }
  61575. // Add UVs and get back to world
  61576. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61577. var vertex = faceVertices[vIndex];
  61578. //TODO check for Int32Array | Uint32Array | Uint16Array
  61579. vertexData.indices.push(currentVertexDataIndex);
  61580. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61581. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61582. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61583. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61584. currentVertexDataIndex++;
  61585. }
  61586. }
  61587. // Return mesh
  61588. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61589. vertexData.applyToMesh(decal);
  61590. decal.position = position.clone();
  61591. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61592. return decal;
  61593. };
  61594. // Privates
  61595. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61596. // extrusion geometry
  61597. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61598. var tangents = path3D.getTangents();
  61599. var normals = path3D.getNormals();
  61600. var binormals = path3D.getBinormals();
  61601. var distances = path3D.getDistances();
  61602. var angle = 0;
  61603. var returnScale = function () { return scale !== null ? scale : 1; };
  61604. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61605. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61606. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61607. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61608. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61609. for (var i = 0; i < curve.length; i++) {
  61610. var shapePath = new Array();
  61611. var angleStep = rotate(i, distances[i]);
  61612. var scaleRatio = scl(i, distances[i]);
  61613. for (var p = 0; p < shape.length; p++) {
  61614. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61615. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61616. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61617. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61618. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61619. shapePath[p] = rotated;
  61620. }
  61621. shapePaths[index] = shapePath;
  61622. angle += angleStep;
  61623. index++;
  61624. }
  61625. // cap
  61626. var capPath = function (shapePath) {
  61627. var pointCap = Array();
  61628. var barycenter = BABYLON.Vector3.Zero();
  61629. var i;
  61630. for (i = 0; i < shapePath.length; i++) {
  61631. barycenter.addInPlace(shapePath[i]);
  61632. }
  61633. barycenter.scaleInPlace(1.0 / shapePath.length);
  61634. for (i = 0; i < shapePath.length; i++) {
  61635. pointCap.push(barycenter);
  61636. }
  61637. return pointCap;
  61638. };
  61639. switch (cap) {
  61640. case BABYLON.Mesh.NO_CAP:
  61641. break;
  61642. case BABYLON.Mesh.CAP_START:
  61643. shapePaths[0] = capPath(shapePaths[2]);
  61644. shapePaths[1] = shapePaths[2];
  61645. break;
  61646. case BABYLON.Mesh.CAP_END:
  61647. shapePaths[index] = shapePaths[index - 1];
  61648. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61649. break;
  61650. case BABYLON.Mesh.CAP_ALL:
  61651. shapePaths[0] = capPath(shapePaths[2]);
  61652. shapePaths[1] = shapePaths[2];
  61653. shapePaths[index] = shapePaths[index - 1];
  61654. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61655. break;
  61656. default:
  61657. break;
  61658. }
  61659. return shapePaths;
  61660. };
  61661. var path3D;
  61662. var pathArray;
  61663. if (instance) { // instance update
  61664. path3D = (instance.path3D).update(curve);
  61665. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61666. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61667. return instance;
  61668. }
  61669. // extruded shape creation
  61670. path3D = new BABYLON.Path3D(curve);
  61671. var newShapePaths = new Array();
  61672. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61673. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61674. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61675. extrudedGeneric.pathArray = pathArray;
  61676. extrudedGeneric.path3D = path3D;
  61677. extrudedGeneric.cap = cap;
  61678. return extrudedGeneric;
  61679. };
  61680. return MeshBuilder;
  61681. }());
  61682. BABYLON.MeshBuilder = MeshBuilder;
  61683. })(BABYLON || (BABYLON = {}));
  61684. //# sourceMappingURL=babylon.meshBuilder.js.map
  61685. var BABYLON;
  61686. (function (BABYLON) {
  61687. /**
  61688. * Draco compression (https://google.github.io/draco/)
  61689. */
  61690. var DracoCompression = /** @class */ (function () {
  61691. /**
  61692. * Constructor
  61693. */
  61694. function DracoCompression() {
  61695. }
  61696. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61697. /**
  61698. * Returns true if the decoder is available.
  61699. */
  61700. get: function () {
  61701. if (typeof DracoDecoderModule !== "undefined") {
  61702. return true;
  61703. }
  61704. var decoder = DracoCompression.Configuration.decoder;
  61705. if (decoder) {
  61706. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61707. return true;
  61708. }
  61709. if (decoder.fallbackUrl) {
  61710. return true;
  61711. }
  61712. }
  61713. return false;
  61714. },
  61715. enumerable: true,
  61716. configurable: true
  61717. });
  61718. /**
  61719. * Stop all async operations and release resources.
  61720. */
  61721. DracoCompression.prototype.dispose = function () {
  61722. };
  61723. /**
  61724. * Decode Draco compressed mesh data to vertex data.
  61725. * @param data The array buffer view for the Draco compression data
  61726. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61727. * @returns A promise that resolves with the decoded vertex data
  61728. */
  61729. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61730. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61731. var module = wrappedModule.module;
  61732. var vertexData = new BABYLON.VertexData();
  61733. var buffer = new module.DecoderBuffer();
  61734. buffer.Init(data, data.byteLength);
  61735. var decoder = new module.Decoder();
  61736. var geometry;
  61737. var status;
  61738. try {
  61739. var type = decoder.GetEncodedGeometryType(buffer);
  61740. switch (type) {
  61741. case module.TRIANGULAR_MESH:
  61742. geometry = new module.Mesh();
  61743. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61744. break;
  61745. case module.POINT_CLOUD:
  61746. geometry = new module.PointCloud();
  61747. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61748. break;
  61749. default:
  61750. throw new Error("Invalid geometry type " + type);
  61751. }
  61752. if (!status.ok() || !geometry.ptr) {
  61753. throw new Error(status.error_msg());
  61754. }
  61755. var numPoints = geometry.num_points();
  61756. if (type === module.TRIANGULAR_MESH) {
  61757. var numFaces = geometry.num_faces();
  61758. var faceIndices = new module.DracoInt32Array();
  61759. try {
  61760. var indices = new Uint32Array(numFaces * 3);
  61761. for (var i = 0; i < numFaces; i++) {
  61762. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61763. var offset = i * 3;
  61764. indices[offset + 0] = faceIndices.GetValue(0);
  61765. indices[offset + 1] = faceIndices.GetValue(1);
  61766. indices[offset + 2] = faceIndices.GetValue(2);
  61767. }
  61768. vertexData.indices = indices;
  61769. }
  61770. finally {
  61771. module.destroy(faceIndices);
  61772. }
  61773. }
  61774. for (var kind in attributes) {
  61775. var uniqueId = attributes[kind];
  61776. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61777. var dracoData = new module.DracoFloat32Array();
  61778. try {
  61779. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61780. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61781. for (var i = 0; i < babylonData.length; i++) {
  61782. babylonData[i] = dracoData.GetValue(i);
  61783. }
  61784. vertexData.set(babylonData, kind);
  61785. }
  61786. finally {
  61787. module.destroy(dracoData);
  61788. }
  61789. }
  61790. }
  61791. finally {
  61792. if (geometry) {
  61793. module.destroy(geometry);
  61794. }
  61795. module.destroy(decoder);
  61796. module.destroy(buffer);
  61797. }
  61798. return vertexData;
  61799. });
  61800. };
  61801. DracoCompression._GetDecoderModule = function () {
  61802. if (!DracoCompression._DecoderModulePromise) {
  61803. var promise = null;
  61804. var config_1 = {};
  61805. if (typeof DracoDecoderModule !== "undefined") {
  61806. promise = Promise.resolve();
  61807. }
  61808. else {
  61809. var decoder = DracoCompression.Configuration.decoder;
  61810. if (decoder) {
  61811. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61812. promise = Promise.all([
  61813. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61814. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61815. config_1.wasmBinary = data;
  61816. })
  61817. ]);
  61818. }
  61819. else if (decoder.fallbackUrl) {
  61820. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61821. }
  61822. }
  61823. }
  61824. if (!promise) {
  61825. throw new Error("Draco decoder module is not available");
  61826. }
  61827. DracoCompression._DecoderModulePromise = promise.then(function () {
  61828. return new Promise(function (resolve) {
  61829. config_1.onModuleLoaded = function (decoderModule) {
  61830. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61831. resolve({ module: decoderModule });
  61832. };
  61833. DracoDecoderModule(config_1);
  61834. });
  61835. });
  61836. }
  61837. return DracoCompression._DecoderModulePromise;
  61838. };
  61839. DracoCompression._LoadScriptAsync = function (url) {
  61840. return new Promise(function (resolve, reject) {
  61841. BABYLON.Tools.LoadScript(url, function () {
  61842. resolve();
  61843. }, function (message) {
  61844. reject(new Error(message));
  61845. });
  61846. });
  61847. };
  61848. DracoCompression._LoadFileAsync = function (url) {
  61849. return new Promise(function (resolve, reject) {
  61850. BABYLON.Tools.LoadFile(url, function (data) {
  61851. resolve(data);
  61852. }, undefined, undefined, true, function (request, exception) {
  61853. reject(exception);
  61854. });
  61855. });
  61856. };
  61857. /**
  61858. * The configuration.
  61859. */
  61860. DracoCompression.Configuration = {
  61861. decoder: {
  61862. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61863. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61864. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61865. }
  61866. };
  61867. return DracoCompression;
  61868. }());
  61869. BABYLON.DracoCompression = DracoCompression;
  61870. })(BABYLON || (BABYLON = {}));
  61871. //# sourceMappingURL=babylon.dracoCompression.js.map
  61872. var BABYLON;
  61873. (function (BABYLON) {
  61874. var AudioEngine = /** @class */ (function () {
  61875. function AudioEngine() {
  61876. this._audioContext = null;
  61877. this._audioContextInitialized = false;
  61878. this.canUseWebAudio = false;
  61879. this.WarnedWebAudioUnsupported = false;
  61880. this.unlocked = false;
  61881. this.isMP3supported = false;
  61882. this.isOGGsupported = false;
  61883. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61884. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61885. this.canUseWebAudio = true;
  61886. }
  61887. var audioElem = document.createElement('audio');
  61888. try {
  61889. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61890. this.isMP3supported = true;
  61891. }
  61892. }
  61893. catch (e) {
  61894. // protect error during capability check.
  61895. }
  61896. try {
  61897. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61898. this.isOGGsupported = true;
  61899. }
  61900. }
  61901. catch (e) {
  61902. // protect error during capability check.
  61903. }
  61904. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61905. this._unlockiOSaudio();
  61906. }
  61907. else {
  61908. this.unlocked = true;
  61909. }
  61910. }
  61911. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61912. get: function () {
  61913. if (!this._audioContextInitialized) {
  61914. this._initializeAudioContext();
  61915. }
  61916. return this._audioContext;
  61917. },
  61918. enumerable: true,
  61919. configurable: true
  61920. });
  61921. AudioEngine.prototype._unlockiOSaudio = function () {
  61922. var _this = this;
  61923. var unlockaudio = function () {
  61924. if (!_this.audioContext) {
  61925. return;
  61926. }
  61927. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61928. var source = _this.audioContext.createBufferSource();
  61929. source.buffer = buffer;
  61930. source.connect(_this.audioContext.destination);
  61931. source.start(0);
  61932. setTimeout(function () {
  61933. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61934. _this.unlocked = true;
  61935. window.removeEventListener('touchend', unlockaudio, false);
  61936. if (_this.onAudioUnlocked) {
  61937. _this.onAudioUnlocked();
  61938. }
  61939. }
  61940. }, 0);
  61941. };
  61942. window.addEventListener('touchend', unlockaudio, false);
  61943. };
  61944. AudioEngine.prototype._initializeAudioContext = function () {
  61945. try {
  61946. if (this.canUseWebAudio) {
  61947. this._audioContext = new AudioContext();
  61948. // create a global volume gain node
  61949. this.masterGain = this._audioContext.createGain();
  61950. this.masterGain.gain.value = 1;
  61951. this.masterGain.connect(this._audioContext.destination);
  61952. this._audioContextInitialized = true;
  61953. }
  61954. }
  61955. catch (e) {
  61956. this.canUseWebAudio = false;
  61957. BABYLON.Tools.Error("Web Audio: " + e.message);
  61958. }
  61959. };
  61960. AudioEngine.prototype.dispose = function () {
  61961. if (this.canUseWebAudio && this._audioContextInitialized) {
  61962. if (this._connectedAnalyser && this._audioContext) {
  61963. this._connectedAnalyser.stopDebugCanvas();
  61964. this._connectedAnalyser.dispose();
  61965. this.masterGain.disconnect();
  61966. this.masterGain.connect(this._audioContext.destination);
  61967. this._connectedAnalyser = null;
  61968. }
  61969. this.masterGain.gain.value = 1;
  61970. }
  61971. this.WarnedWebAudioUnsupported = false;
  61972. };
  61973. AudioEngine.prototype.getGlobalVolume = function () {
  61974. if (this.canUseWebAudio && this._audioContextInitialized) {
  61975. return this.masterGain.gain.value;
  61976. }
  61977. else {
  61978. return -1;
  61979. }
  61980. };
  61981. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61982. if (this.canUseWebAudio && this._audioContextInitialized) {
  61983. this.masterGain.gain.value = newVolume;
  61984. }
  61985. };
  61986. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61987. if (this._connectedAnalyser) {
  61988. this._connectedAnalyser.stopDebugCanvas();
  61989. }
  61990. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61991. this._connectedAnalyser = analyser;
  61992. this.masterGain.disconnect();
  61993. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61994. }
  61995. };
  61996. return AudioEngine;
  61997. }());
  61998. BABYLON.AudioEngine = AudioEngine;
  61999. })(BABYLON || (BABYLON = {}));
  62000. //# sourceMappingURL=babylon.audioEngine.js.map
  62001. var BABYLON;
  62002. (function (BABYLON) {
  62003. var Sound = /** @class */ (function () {
  62004. /**
  62005. * Create a sound and attach it to a scene
  62006. * @param name Name of your sound
  62007. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62008. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62009. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62010. */
  62011. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62012. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62013. var _this = this;
  62014. this.autoplay = false;
  62015. this.loop = false;
  62016. this.useCustomAttenuation = false;
  62017. this.spatialSound = false;
  62018. this.refDistance = 1;
  62019. this.rolloffFactor = 1;
  62020. this.maxDistance = 100;
  62021. this.distanceModel = "linear";
  62022. this._panningModel = "equalpower";
  62023. this._playbackRate = 1;
  62024. this._streaming = false;
  62025. this._startTime = 0;
  62026. this._startOffset = 0;
  62027. this._position = BABYLON.Vector3.Zero();
  62028. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62029. this._volume = 1;
  62030. this._isReadyToPlay = false;
  62031. this.isPlaying = false;
  62032. this.isPaused = false;
  62033. this._isDirectional = false;
  62034. // Used if you'd like to create a directional sound.
  62035. // If not set, the sound will be omnidirectional
  62036. this._coneInnerAngle = 360;
  62037. this._coneOuterAngle = 360;
  62038. this._coneOuterGain = 0;
  62039. this._isOutputConnected = false;
  62040. this._urlType = "Unknown";
  62041. this.name = name;
  62042. this._scene = scene;
  62043. this._readyToPlayCallback = readyToPlayCallback;
  62044. // Default custom attenuation function is a linear attenuation
  62045. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62046. if (currentDistance < maxDistance) {
  62047. return currentVolume * (1 - currentDistance / maxDistance);
  62048. }
  62049. else {
  62050. return 0;
  62051. }
  62052. };
  62053. if (options) {
  62054. this.autoplay = options.autoplay || false;
  62055. this.loop = options.loop || false;
  62056. // if volume === 0, we need another way to check this option
  62057. if (options.volume !== undefined) {
  62058. this._volume = options.volume;
  62059. }
  62060. this.spatialSound = options.spatialSound || false;
  62061. this.maxDistance = options.maxDistance || 100;
  62062. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62063. this.rolloffFactor = options.rolloffFactor || 1;
  62064. this.refDistance = options.refDistance || 1;
  62065. this.distanceModel = options.distanceModel || "linear";
  62066. this._playbackRate = options.playbackRate || 1;
  62067. this._streaming = options.streaming || false;
  62068. }
  62069. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62070. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62071. this._soundGain.gain.value = this._volume;
  62072. this._inputAudioNode = this._soundGain;
  62073. this._ouputAudioNode = this._soundGain;
  62074. if (this.spatialSound) {
  62075. this._createSpatialParameters();
  62076. }
  62077. this._scene.mainSoundTrack.AddSound(this);
  62078. var validParameter = true;
  62079. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62080. if (urlOrArrayBuffer) {
  62081. try {
  62082. if (typeof (urlOrArrayBuffer) === "string")
  62083. this._urlType = "String";
  62084. if (Array.isArray(urlOrArrayBuffer))
  62085. this._urlType = "Array";
  62086. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62087. this._urlType = "ArrayBuffer";
  62088. var urls = [];
  62089. var codecSupportedFound = false;
  62090. switch (this._urlType) {
  62091. case "ArrayBuffer":
  62092. if (urlOrArrayBuffer.byteLength > 0) {
  62093. codecSupportedFound = true;
  62094. this._soundLoaded(urlOrArrayBuffer);
  62095. }
  62096. break;
  62097. case "String":
  62098. urls.push(urlOrArrayBuffer);
  62099. case "Array":
  62100. if (urls.length === 0)
  62101. urls = urlOrArrayBuffer;
  62102. // If we found a supported format, we load it immediately and stop the loop
  62103. for (var i = 0; i < urls.length; i++) {
  62104. var url = urls[i];
  62105. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62106. codecSupportedFound = true;
  62107. }
  62108. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62109. codecSupportedFound = true;
  62110. }
  62111. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62112. codecSupportedFound = true;
  62113. }
  62114. if (url.indexOf("blob:") !== -1) {
  62115. codecSupportedFound = true;
  62116. }
  62117. if (codecSupportedFound) {
  62118. // Loading sound using XHR2
  62119. if (!this._streaming) {
  62120. this._scene._loadFile(url, function (data) {
  62121. _this._soundLoaded(data);
  62122. }, undefined, true, true, function (exception) {
  62123. if (exception) {
  62124. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62125. }
  62126. BABYLON.Tools.Error("Sound creation aborted.");
  62127. _this._scene.mainSoundTrack.RemoveSound(_this);
  62128. });
  62129. }
  62130. // Streaming sound using HTML5 Audio tag
  62131. else {
  62132. this._htmlAudioElement = new Audio(url);
  62133. this._htmlAudioElement.controls = false;
  62134. this._htmlAudioElement.loop = this.loop;
  62135. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62136. this._htmlAudioElement.preload = "auto";
  62137. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62138. _this._isReadyToPlay = true;
  62139. if (_this.autoplay) {
  62140. _this.play();
  62141. }
  62142. if (_this._readyToPlayCallback) {
  62143. _this._readyToPlayCallback();
  62144. }
  62145. });
  62146. document.body.appendChild(this._htmlAudioElement);
  62147. }
  62148. break;
  62149. }
  62150. }
  62151. break;
  62152. default:
  62153. validParameter = false;
  62154. break;
  62155. }
  62156. if (!validParameter) {
  62157. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62158. }
  62159. else {
  62160. if (!codecSupportedFound) {
  62161. this._isReadyToPlay = true;
  62162. // Simulating a ready to play event to avoid breaking code path
  62163. if (this._readyToPlayCallback) {
  62164. window.setTimeout(function () {
  62165. if (_this._readyToPlayCallback) {
  62166. _this._readyToPlayCallback();
  62167. }
  62168. }, 1000);
  62169. }
  62170. }
  62171. }
  62172. }
  62173. catch (ex) {
  62174. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62175. this._scene.mainSoundTrack.RemoveSound(this);
  62176. }
  62177. }
  62178. }
  62179. else {
  62180. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62181. this._scene.mainSoundTrack.AddSound(this);
  62182. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62183. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62184. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62185. }
  62186. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62187. if (this._readyToPlayCallback) {
  62188. window.setTimeout(function () {
  62189. if (_this._readyToPlayCallback) {
  62190. _this._readyToPlayCallback();
  62191. }
  62192. }, 1000);
  62193. }
  62194. }
  62195. }
  62196. Sound.prototype.dispose = function () {
  62197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62198. if (this.isPlaying) {
  62199. this.stop();
  62200. }
  62201. this._isReadyToPlay = false;
  62202. if (this.soundTrackId === -1) {
  62203. this._scene.mainSoundTrack.RemoveSound(this);
  62204. }
  62205. else {
  62206. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62207. }
  62208. if (this._soundGain) {
  62209. this._soundGain.disconnect();
  62210. this._soundGain = null;
  62211. }
  62212. if (this._soundPanner) {
  62213. this._soundPanner.disconnect();
  62214. this._soundPanner = null;
  62215. }
  62216. if (this._soundSource) {
  62217. this._soundSource.disconnect();
  62218. this._soundSource = null;
  62219. }
  62220. this._audioBuffer = null;
  62221. if (this._htmlAudioElement) {
  62222. this._htmlAudioElement.pause();
  62223. this._htmlAudioElement.src = "";
  62224. document.body.removeChild(this._htmlAudioElement);
  62225. }
  62226. if (this._connectedMesh && this._registerFunc) {
  62227. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62228. this._connectedMesh = null;
  62229. }
  62230. }
  62231. };
  62232. Sound.prototype.isReady = function () {
  62233. return this._isReadyToPlay;
  62234. };
  62235. Sound.prototype._soundLoaded = function (audioData) {
  62236. var _this = this;
  62237. if (!BABYLON.Engine.audioEngine.audioContext) {
  62238. return;
  62239. }
  62240. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62241. _this._audioBuffer = buffer;
  62242. _this._isReadyToPlay = true;
  62243. if (_this.autoplay) {
  62244. _this.play();
  62245. }
  62246. if (_this._readyToPlayCallback) {
  62247. _this._readyToPlayCallback();
  62248. }
  62249. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62250. };
  62251. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62252. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62253. this._audioBuffer = audioBuffer;
  62254. this._isReadyToPlay = true;
  62255. }
  62256. };
  62257. Sound.prototype.updateOptions = function (options) {
  62258. if (options) {
  62259. this.loop = options.loop || this.loop;
  62260. this.maxDistance = options.maxDistance || this.maxDistance;
  62261. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62262. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62263. this.refDistance = options.refDistance || this.refDistance;
  62264. this.distanceModel = options.distanceModel || this.distanceModel;
  62265. this._playbackRate = options.playbackRate || this._playbackRate;
  62266. this._updateSpatialParameters();
  62267. if (this.isPlaying) {
  62268. if (this._streaming) {
  62269. this._htmlAudioElement.playbackRate = this._playbackRate;
  62270. }
  62271. else {
  62272. if (this._soundSource) {
  62273. this._soundSource.playbackRate.value = this._playbackRate;
  62274. }
  62275. }
  62276. }
  62277. }
  62278. };
  62279. Sound.prototype._createSpatialParameters = function () {
  62280. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62281. if (this._scene.headphone) {
  62282. this._panningModel = "HRTF";
  62283. }
  62284. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62285. this._updateSpatialParameters();
  62286. this._soundPanner.connect(this._ouputAudioNode);
  62287. this._inputAudioNode = this._soundPanner;
  62288. }
  62289. };
  62290. Sound.prototype._updateSpatialParameters = function () {
  62291. if (this.spatialSound && this._soundPanner) {
  62292. if (this.useCustomAttenuation) {
  62293. // Tricks to disable in a way embedded Web Audio attenuation
  62294. this._soundPanner.distanceModel = "linear";
  62295. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62296. this._soundPanner.refDistance = 1;
  62297. this._soundPanner.rolloffFactor = 1;
  62298. this._soundPanner.panningModel = this._panningModel;
  62299. }
  62300. else {
  62301. this._soundPanner.distanceModel = this.distanceModel;
  62302. this._soundPanner.maxDistance = this.maxDistance;
  62303. this._soundPanner.refDistance = this.refDistance;
  62304. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62305. this._soundPanner.panningModel = this._panningModel;
  62306. }
  62307. }
  62308. };
  62309. Sound.prototype.switchPanningModelToHRTF = function () {
  62310. this._panningModel = "HRTF";
  62311. this._switchPanningModel();
  62312. };
  62313. Sound.prototype.switchPanningModelToEqualPower = function () {
  62314. this._panningModel = "equalpower";
  62315. this._switchPanningModel();
  62316. };
  62317. Sound.prototype._switchPanningModel = function () {
  62318. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62319. this._soundPanner.panningModel = this._panningModel;
  62320. }
  62321. };
  62322. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62323. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62324. if (this._isOutputConnected) {
  62325. this._ouputAudioNode.disconnect();
  62326. }
  62327. this._ouputAudioNode.connect(soundTrackAudioNode);
  62328. this._isOutputConnected = true;
  62329. }
  62330. };
  62331. /**
  62332. * Transform this sound into a directional source
  62333. * @param coneInnerAngle Size of the inner cone in degree
  62334. * @param coneOuterAngle Size of the outer cone in degree
  62335. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62336. */
  62337. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62338. if (coneOuterAngle < coneInnerAngle) {
  62339. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62340. return;
  62341. }
  62342. this._coneInnerAngle = coneInnerAngle;
  62343. this._coneOuterAngle = coneOuterAngle;
  62344. this._coneOuterGain = coneOuterGain;
  62345. this._isDirectional = true;
  62346. if (this.isPlaying && this.loop) {
  62347. this.stop();
  62348. this.play();
  62349. }
  62350. };
  62351. Sound.prototype.setPosition = function (newPosition) {
  62352. this._position = newPosition;
  62353. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62354. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62355. }
  62356. };
  62357. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62358. this._localDirection = newLocalDirection;
  62359. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62360. this._updateDirection();
  62361. }
  62362. };
  62363. Sound.prototype._updateDirection = function () {
  62364. if (!this._connectedMesh || !this._soundPanner) {
  62365. return;
  62366. }
  62367. var mat = this._connectedMesh.getWorldMatrix();
  62368. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62369. direction.normalize();
  62370. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62371. };
  62372. Sound.prototype.updateDistanceFromListener = function () {
  62373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62374. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62375. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62376. }
  62377. };
  62378. Sound.prototype.setAttenuationFunction = function (callback) {
  62379. this._customAttenuationFunction = callback;
  62380. };
  62381. /**
  62382. * Play the sound
  62383. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62384. * @param offset (optional) Start the sound setting it at a specific time
  62385. */
  62386. Sound.prototype.play = function (time, offset) {
  62387. var _this = this;
  62388. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62389. try {
  62390. if (this._startOffset < 0) {
  62391. time = -this._startOffset;
  62392. this._startOffset = 0;
  62393. }
  62394. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62395. if (!this._soundSource || !this._streamingSource) {
  62396. if (this.spatialSound && this._soundPanner) {
  62397. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62398. if (this._isDirectional) {
  62399. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62400. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62401. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62402. if (this._connectedMesh) {
  62403. this._updateDirection();
  62404. }
  62405. else {
  62406. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62407. }
  62408. }
  62409. }
  62410. }
  62411. if (this._streaming) {
  62412. if (!this._streamingSource) {
  62413. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62414. this._htmlAudioElement.onended = function () { _this._onended(); };
  62415. this._htmlAudioElement.playbackRate = this._playbackRate;
  62416. }
  62417. this._streamingSource.disconnect();
  62418. this._streamingSource.connect(this._inputAudioNode);
  62419. this._htmlAudioElement.play();
  62420. }
  62421. else {
  62422. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62423. this._soundSource.buffer = this._audioBuffer;
  62424. this._soundSource.connect(this._inputAudioNode);
  62425. this._soundSource.loop = this.loop;
  62426. this._soundSource.playbackRate.value = this._playbackRate;
  62427. this._soundSource.onended = function () { _this._onended(); };
  62428. if (this._soundSource.buffer) {
  62429. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62430. }
  62431. }
  62432. this._startTime = startTime;
  62433. this.isPlaying = true;
  62434. this.isPaused = false;
  62435. }
  62436. catch (ex) {
  62437. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62438. }
  62439. }
  62440. };
  62441. Sound.prototype._onended = function () {
  62442. this.isPlaying = false;
  62443. if (this.onended) {
  62444. this.onended();
  62445. }
  62446. };
  62447. /**
  62448. * Stop the sound
  62449. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62450. */
  62451. Sound.prototype.stop = function (time) {
  62452. if (this.isPlaying) {
  62453. if (this._streaming) {
  62454. this._htmlAudioElement.pause();
  62455. // Test needed for Firefox or it will generate an Invalid State Error
  62456. if (this._htmlAudioElement.currentTime > 0) {
  62457. this._htmlAudioElement.currentTime = 0;
  62458. }
  62459. }
  62460. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62461. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62462. this._soundSource.stop(stopTime);
  62463. this._soundSource.onended = function () { };
  62464. if (!this.isPaused) {
  62465. this._startOffset = 0;
  62466. }
  62467. }
  62468. this.isPlaying = false;
  62469. }
  62470. };
  62471. Sound.prototype.pause = function () {
  62472. if (this.isPlaying) {
  62473. this.isPaused = true;
  62474. if (this._streaming) {
  62475. this._htmlAudioElement.pause();
  62476. }
  62477. else if (BABYLON.Engine.audioEngine.audioContext) {
  62478. this.stop(0);
  62479. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62480. }
  62481. }
  62482. };
  62483. Sound.prototype.setVolume = function (newVolume, time) {
  62484. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62485. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62486. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62487. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62488. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62489. }
  62490. else {
  62491. this._soundGain.gain.value = newVolume;
  62492. }
  62493. }
  62494. this._volume = newVolume;
  62495. };
  62496. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62497. this._playbackRate = newPlaybackRate;
  62498. if (this.isPlaying) {
  62499. if (this._streaming) {
  62500. this._htmlAudioElement.playbackRate = this._playbackRate;
  62501. }
  62502. else if (this._soundSource) {
  62503. this._soundSource.playbackRate.value = this._playbackRate;
  62504. }
  62505. }
  62506. };
  62507. Sound.prototype.getVolume = function () {
  62508. return this._volume;
  62509. };
  62510. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62511. var _this = this;
  62512. if (this._connectedMesh && this._registerFunc) {
  62513. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62514. this._registerFunc = null;
  62515. }
  62516. this._connectedMesh = meshToConnectTo;
  62517. if (!this.spatialSound) {
  62518. this.spatialSound = true;
  62519. this._createSpatialParameters();
  62520. if (this.isPlaying && this.loop) {
  62521. this.stop();
  62522. this.play();
  62523. }
  62524. }
  62525. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62526. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62527. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62528. };
  62529. Sound.prototype.detachFromMesh = function () {
  62530. if (this._connectedMesh && this._registerFunc) {
  62531. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62532. this._registerFunc = null;
  62533. this._connectedMesh = null;
  62534. }
  62535. };
  62536. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62537. if (!node.getBoundingInfo) {
  62538. return;
  62539. }
  62540. var mesh = node;
  62541. var boundingInfo = mesh.getBoundingInfo();
  62542. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62543. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62544. this._updateDirection();
  62545. }
  62546. };
  62547. Sound.prototype.clone = function () {
  62548. var _this = this;
  62549. if (!this._streaming) {
  62550. var setBufferAndRun = function () {
  62551. if (_this._isReadyToPlay) {
  62552. clonedSound._audioBuffer = _this.getAudioBuffer();
  62553. clonedSound._isReadyToPlay = true;
  62554. if (clonedSound.autoplay) {
  62555. clonedSound.play();
  62556. }
  62557. }
  62558. else {
  62559. window.setTimeout(setBufferAndRun, 300);
  62560. }
  62561. };
  62562. var currentOptions = {
  62563. autoplay: this.autoplay, loop: this.loop,
  62564. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62565. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62566. refDistance: this.refDistance, distanceModel: this.distanceModel
  62567. };
  62568. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62569. if (this.useCustomAttenuation) {
  62570. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62571. }
  62572. clonedSound.setPosition(this._position);
  62573. clonedSound.setPlaybackRate(this._playbackRate);
  62574. setBufferAndRun();
  62575. return clonedSound;
  62576. }
  62577. // Can't clone a streaming sound
  62578. else {
  62579. return null;
  62580. }
  62581. };
  62582. Sound.prototype.getAudioBuffer = function () {
  62583. return this._audioBuffer;
  62584. };
  62585. Sound.prototype.serialize = function () {
  62586. var serializationObject = {
  62587. name: this.name,
  62588. url: this.name,
  62589. autoplay: this.autoplay,
  62590. loop: this.loop,
  62591. volume: this._volume,
  62592. spatialSound: this.spatialSound,
  62593. maxDistance: this.maxDistance,
  62594. rolloffFactor: this.rolloffFactor,
  62595. refDistance: this.refDistance,
  62596. distanceModel: this.distanceModel,
  62597. playbackRate: this._playbackRate,
  62598. panningModel: this._panningModel,
  62599. soundTrackId: this.soundTrackId
  62600. };
  62601. if (this.spatialSound) {
  62602. if (this._connectedMesh)
  62603. serializationObject.connectedMeshId = this._connectedMesh.id;
  62604. serializationObject.position = this._position.asArray();
  62605. serializationObject.refDistance = this.refDistance;
  62606. serializationObject.distanceModel = this.distanceModel;
  62607. serializationObject.isDirectional = this._isDirectional;
  62608. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62609. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62610. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62611. serializationObject.coneOuterGain = this._coneOuterGain;
  62612. }
  62613. return serializationObject;
  62614. };
  62615. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62616. var soundName = parsedSound.name;
  62617. var soundUrl;
  62618. if (parsedSound.url) {
  62619. soundUrl = rootUrl + parsedSound.url;
  62620. }
  62621. else {
  62622. soundUrl = rootUrl + soundName;
  62623. }
  62624. var options = {
  62625. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62626. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62627. rolloffFactor: parsedSound.rolloffFactor,
  62628. refDistance: parsedSound.refDistance,
  62629. distanceModel: parsedSound.distanceModel,
  62630. playbackRate: parsedSound.playbackRate
  62631. };
  62632. var newSound;
  62633. if (!sourceSound) {
  62634. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62635. scene._addPendingData(newSound);
  62636. }
  62637. else {
  62638. var setBufferAndRun = function () {
  62639. if (sourceSound._isReadyToPlay) {
  62640. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62641. newSound._isReadyToPlay = true;
  62642. if (newSound.autoplay) {
  62643. newSound.play();
  62644. }
  62645. }
  62646. else {
  62647. window.setTimeout(setBufferAndRun, 300);
  62648. }
  62649. };
  62650. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62651. setBufferAndRun();
  62652. }
  62653. if (parsedSound.position) {
  62654. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62655. newSound.setPosition(soundPosition);
  62656. }
  62657. if (parsedSound.isDirectional) {
  62658. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62659. if (parsedSound.localDirectionToMesh) {
  62660. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62661. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62662. }
  62663. }
  62664. if (parsedSound.connectedMeshId) {
  62665. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62666. if (connectedMesh) {
  62667. newSound.attachToMesh(connectedMesh);
  62668. }
  62669. }
  62670. return newSound;
  62671. };
  62672. return Sound;
  62673. }());
  62674. BABYLON.Sound = Sound;
  62675. })(BABYLON || (BABYLON = {}));
  62676. //# sourceMappingURL=babylon.sound.js.map
  62677. var BABYLON;
  62678. (function (BABYLON) {
  62679. var SoundTrack = /** @class */ (function () {
  62680. function SoundTrack(scene, options) {
  62681. this.id = -1;
  62682. this._isMainTrack = false;
  62683. this._isInitialized = false;
  62684. this._scene = scene;
  62685. this.soundCollection = new Array();
  62686. this._options = options;
  62687. if (!this._isMainTrack) {
  62688. this._scene.soundTracks.push(this);
  62689. this.id = this._scene.soundTracks.length - 1;
  62690. }
  62691. }
  62692. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62693. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62694. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62695. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62696. if (this._options) {
  62697. if (this._options.volume) {
  62698. this._outputAudioNode.gain.value = this._options.volume;
  62699. }
  62700. if (this._options.mainTrack) {
  62701. this._isMainTrack = this._options.mainTrack;
  62702. }
  62703. }
  62704. this._isInitialized = true;
  62705. }
  62706. };
  62707. SoundTrack.prototype.dispose = function () {
  62708. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62709. if (this._connectedAnalyser) {
  62710. this._connectedAnalyser.stopDebugCanvas();
  62711. }
  62712. while (this.soundCollection.length) {
  62713. this.soundCollection[0].dispose();
  62714. }
  62715. if (this._outputAudioNode) {
  62716. this._outputAudioNode.disconnect();
  62717. }
  62718. this._outputAudioNode = null;
  62719. }
  62720. };
  62721. SoundTrack.prototype.AddSound = function (sound) {
  62722. if (!this._isInitialized) {
  62723. this._initializeSoundTrackAudioGraph();
  62724. }
  62725. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62726. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62727. }
  62728. if (sound.soundTrackId) {
  62729. if (sound.soundTrackId === -1) {
  62730. this._scene.mainSoundTrack.RemoveSound(sound);
  62731. }
  62732. else {
  62733. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62734. }
  62735. }
  62736. this.soundCollection.push(sound);
  62737. sound.soundTrackId = this.id;
  62738. };
  62739. SoundTrack.prototype.RemoveSound = function (sound) {
  62740. var index = this.soundCollection.indexOf(sound);
  62741. if (index !== -1) {
  62742. this.soundCollection.splice(index, 1);
  62743. }
  62744. };
  62745. SoundTrack.prototype.setVolume = function (newVolume) {
  62746. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62747. this._outputAudioNode.gain.value = newVolume;
  62748. }
  62749. };
  62750. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62751. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62752. for (var i = 0; i < this.soundCollection.length; i++) {
  62753. this.soundCollection[i].switchPanningModelToHRTF();
  62754. }
  62755. }
  62756. };
  62757. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62758. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62759. for (var i = 0; i < this.soundCollection.length; i++) {
  62760. this.soundCollection[i].switchPanningModelToEqualPower();
  62761. }
  62762. }
  62763. };
  62764. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62765. if (this._connectedAnalyser) {
  62766. this._connectedAnalyser.stopDebugCanvas();
  62767. }
  62768. this._connectedAnalyser = analyser;
  62769. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62770. this._outputAudioNode.disconnect();
  62771. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62772. }
  62773. };
  62774. return SoundTrack;
  62775. }());
  62776. BABYLON.SoundTrack = SoundTrack;
  62777. })(BABYLON || (BABYLON = {}));
  62778. //# sourceMappingURL=babylon.soundtrack.js.map
  62779. var BABYLON;
  62780. (function (BABYLON) {
  62781. /**
  62782. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62783. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62784. */
  62785. var Analyser = /** @class */ (function () {
  62786. /**
  62787. * Creates a new analyser
  62788. * @param scene defines hosting scene
  62789. */
  62790. function Analyser(scene) {
  62791. /**
  62792. * Gets or sets the smoothing
  62793. * @ignorenaming
  62794. */
  62795. this.SMOOTHING = 0.75;
  62796. /**
  62797. * Gets or sets the FFT table size
  62798. * @ignorenaming
  62799. */
  62800. this.FFT_SIZE = 512;
  62801. /**
  62802. * Gets or sets the bar graph amplitude
  62803. * @ignorenaming
  62804. */
  62805. this.BARGRAPHAMPLITUDE = 256;
  62806. /**
  62807. * Gets or sets the position of the debug canvas
  62808. * @ignorenaming
  62809. */
  62810. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62811. /**
  62812. * Gets or sets the debug canvas size
  62813. * @ignorenaming
  62814. */
  62815. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62816. this._scene = scene;
  62817. this._audioEngine = BABYLON.Engine.audioEngine;
  62818. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62819. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62820. this._webAudioAnalyser.minDecibels = -140;
  62821. this._webAudioAnalyser.maxDecibels = 0;
  62822. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62823. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62824. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62825. }
  62826. }
  62827. /**
  62828. * Get the number of data values you will have to play with for the visualization
  62829. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62830. * @returns a number
  62831. */
  62832. Analyser.prototype.getFrequencyBinCount = function () {
  62833. if (this._audioEngine.canUseWebAudio) {
  62834. return this._webAudioAnalyser.frequencyBinCount;
  62835. }
  62836. else {
  62837. return 0;
  62838. }
  62839. };
  62840. /**
  62841. * Gets the current frequency data as a byte array
  62842. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62843. * @returns a Uint8Array
  62844. */
  62845. Analyser.prototype.getByteFrequencyData = function () {
  62846. if (this._audioEngine.canUseWebAudio) {
  62847. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62848. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62849. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62850. }
  62851. return this._byteFreqs;
  62852. };
  62853. /**
  62854. * Gets the current waveform as a byte array
  62855. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62856. * @returns a Uint8Array
  62857. */
  62858. Analyser.prototype.getByteTimeDomainData = function () {
  62859. if (this._audioEngine.canUseWebAudio) {
  62860. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62861. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62862. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62863. }
  62864. return this._byteTime;
  62865. };
  62866. /**
  62867. * Gets the current frequency data as a float array
  62868. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62869. * @returns a Float32Array
  62870. */
  62871. Analyser.prototype.getFloatFrequencyData = function () {
  62872. if (this._audioEngine.canUseWebAudio) {
  62873. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62874. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62875. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62876. }
  62877. return this._floatFreqs;
  62878. };
  62879. /**
  62880. * Renders the debug canvas
  62881. */
  62882. Analyser.prototype.drawDebugCanvas = function () {
  62883. var _this = this;
  62884. if (this._audioEngine.canUseWebAudio) {
  62885. if (!this._debugCanvas) {
  62886. this._debugCanvas = document.createElement("canvas");
  62887. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62888. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62889. this._debugCanvas.style.position = "absolute";
  62890. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62891. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62892. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62893. document.body.appendChild(this._debugCanvas);
  62894. this._registerFunc = function () {
  62895. _this.drawDebugCanvas();
  62896. };
  62897. this._scene.registerBeforeRender(this._registerFunc);
  62898. }
  62899. if (this._registerFunc && this._debugCanvasContext) {
  62900. var workingArray = this.getByteFrequencyData();
  62901. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62902. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62903. // Draw the frequency domain chart.
  62904. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62905. var value = workingArray[i];
  62906. var percent = value / this.BARGRAPHAMPLITUDE;
  62907. var height = this.DEBUGCANVASSIZE.height * percent;
  62908. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62909. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62910. var hue = i / this.getFrequencyBinCount() * 360;
  62911. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62912. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62913. }
  62914. }
  62915. }
  62916. };
  62917. /**
  62918. * Stops rendering the debug canvas and removes it
  62919. */
  62920. Analyser.prototype.stopDebugCanvas = function () {
  62921. if (this._debugCanvas) {
  62922. if (this._registerFunc) {
  62923. this._scene.unregisterBeforeRender(this._registerFunc);
  62924. this._registerFunc = null;
  62925. }
  62926. document.body.removeChild(this._debugCanvas);
  62927. this._debugCanvas = null;
  62928. this._debugCanvasContext = null;
  62929. }
  62930. };
  62931. /**
  62932. * Connects two audio nodes
  62933. * @param inputAudioNode defines first node to connect
  62934. * @param outputAudioNode defines second node to connect
  62935. */
  62936. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62937. if (this._audioEngine.canUseWebAudio) {
  62938. inputAudioNode.connect(this._webAudioAnalyser);
  62939. this._webAudioAnalyser.connect(outputAudioNode);
  62940. }
  62941. };
  62942. /**
  62943. * Releases all associated resources
  62944. */
  62945. Analyser.prototype.dispose = function () {
  62946. if (this._audioEngine.canUseWebAudio) {
  62947. this._webAudioAnalyser.disconnect();
  62948. }
  62949. };
  62950. return Analyser;
  62951. }());
  62952. BABYLON.Analyser = Analyser;
  62953. })(BABYLON || (BABYLON = {}));
  62954. //# sourceMappingURL=babylon.analyser.js.map
  62955. var BABYLON;
  62956. (function (BABYLON) {
  62957. var CubeTexture = /** @class */ (function (_super) {
  62958. __extends(CubeTexture, _super);
  62959. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62960. if (extensions === void 0) { extensions = null; }
  62961. if (noMipmap === void 0) { noMipmap = false; }
  62962. if (files === void 0) { files = null; }
  62963. if (onLoad === void 0) { onLoad = null; }
  62964. if (onError === void 0) { onError = null; }
  62965. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62966. if (prefiltered === void 0) { prefiltered = false; }
  62967. if (forcedExtension === void 0) { forcedExtension = null; }
  62968. var _this = _super.call(this, scene) || this;
  62969. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62970. /**
  62971. * Gets or sets the center of the bounding box associated with the cube texture
  62972. * It must define where the camera used to render the texture was set
  62973. */
  62974. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62975. _this._rotationY = 0;
  62976. _this.name = rootUrl;
  62977. _this.url = rootUrl;
  62978. _this._noMipmap = noMipmap;
  62979. _this.hasAlpha = false;
  62980. _this._format = format;
  62981. _this._prefiltered = prefiltered;
  62982. _this.isCube = true;
  62983. _this._textureMatrix = BABYLON.Matrix.Identity();
  62984. if (prefiltered) {
  62985. _this.gammaSpace = false;
  62986. }
  62987. if (!rootUrl && !files) {
  62988. return _this;
  62989. }
  62990. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62991. var lastDot = rootUrl.lastIndexOf(".");
  62992. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62993. var isDDS = (extension === ".dds");
  62994. if (!files) {
  62995. if (!isDDS && !extensions) {
  62996. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62997. }
  62998. files = [];
  62999. if (extensions) {
  63000. for (var index = 0; index < extensions.length; index++) {
  63001. files.push(rootUrl + extensions[index]);
  63002. }
  63003. }
  63004. }
  63005. _this._files = files;
  63006. if (!_this._texture) {
  63007. if (!scene.useDelayedTextureLoading) {
  63008. if (prefiltered) {
  63009. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63010. }
  63011. else {
  63012. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63013. }
  63014. }
  63015. else {
  63016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63017. }
  63018. }
  63019. else if (onLoad) {
  63020. if (_this._texture.isReady) {
  63021. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63022. }
  63023. else {
  63024. _this._texture.onLoadedObservable.add(onLoad);
  63025. }
  63026. }
  63027. return _this;
  63028. }
  63029. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63030. get: function () {
  63031. return this._boundingBoxSize;
  63032. },
  63033. /**
  63034. * Gets or sets the size of the bounding box associated with the cube texture
  63035. * When defined, the cubemap will switch to local mode
  63036. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63037. * @example https://www.babylonjs-playground.com/#RNASML
  63038. */
  63039. set: function (value) {
  63040. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63041. return;
  63042. }
  63043. this._boundingBoxSize = value;
  63044. var scene = this.getScene();
  63045. if (scene) {
  63046. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63047. }
  63048. },
  63049. enumerable: true,
  63050. configurable: true
  63051. });
  63052. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63053. /**
  63054. * Gets texture matrix rotation angle around Y axis radians.
  63055. */
  63056. get: function () {
  63057. return this._rotationY;
  63058. },
  63059. /**
  63060. * Sets texture matrix rotation angle around Y axis in radians.
  63061. */
  63062. set: function (value) {
  63063. this._rotationY = value;
  63064. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63065. },
  63066. enumerable: true,
  63067. configurable: true
  63068. });
  63069. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63070. var rootUrlKey = "";
  63071. files.forEach(function (url) { return rootUrlKey += url; });
  63072. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63073. };
  63074. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63075. if (forcedExtension === void 0) { forcedExtension = null; }
  63076. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63077. };
  63078. // Methods
  63079. CubeTexture.prototype.delayLoad = function () {
  63080. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63081. return;
  63082. }
  63083. var scene = this.getScene();
  63084. if (!scene) {
  63085. return;
  63086. }
  63087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63088. this._texture = this._getFromCache(this.url, this._noMipmap);
  63089. if (!this._texture) {
  63090. if (this._prefiltered) {
  63091. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63092. }
  63093. else {
  63094. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63095. }
  63096. }
  63097. };
  63098. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63099. return this._textureMatrix;
  63100. };
  63101. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63102. this._textureMatrix = value;
  63103. };
  63104. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63105. var texture = BABYLON.SerializationHelper.Parse(function () {
  63106. var prefiltered = false;
  63107. if (parsedTexture.prefiltered) {
  63108. prefiltered = parsedTexture.prefiltered;
  63109. }
  63110. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63111. }, parsedTexture, scene);
  63112. // Local Cubemaps
  63113. if (parsedTexture.boundingBoxPosition) {
  63114. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63115. }
  63116. if (parsedTexture.boundingBoxSize) {
  63117. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63118. }
  63119. // Animations
  63120. if (parsedTexture.animations) {
  63121. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63122. var parsedAnimation = parsedTexture.animations[animationIndex];
  63123. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63124. }
  63125. }
  63126. return texture;
  63127. };
  63128. CubeTexture.prototype.clone = function () {
  63129. var _this = this;
  63130. return BABYLON.SerializationHelper.Clone(function () {
  63131. var scene = _this.getScene();
  63132. if (!scene) {
  63133. return _this;
  63134. }
  63135. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63136. }, this);
  63137. };
  63138. __decorate([
  63139. BABYLON.serialize("rotationY")
  63140. ], CubeTexture.prototype, "_rotationY", void 0);
  63141. return CubeTexture;
  63142. }(BABYLON.BaseTexture));
  63143. BABYLON.CubeTexture = CubeTexture;
  63144. })(BABYLON || (BABYLON = {}));
  63145. //# sourceMappingURL=babylon.cubeTexture.js.map
  63146. var BABYLON;
  63147. (function (BABYLON) {
  63148. var RenderTargetTexture = /** @class */ (function (_super) {
  63149. __extends(RenderTargetTexture, _super);
  63150. /**
  63151. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63152. * or used a shadow, depth texture...
  63153. * @param name The friendly name of the texture
  63154. * @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)
  63155. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63156. * @param generateMipMaps True if mip maps need to be generated after render.
  63157. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63158. * @param type The type of the buffer in the RTT (int, half float, float...)
  63159. * @param isCube True if a cube texture needs to be created
  63160. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63161. * @param generateDepthBuffer True to generate a depth buffer
  63162. * @param generateStencilBuffer True to generate a stencil buffer
  63163. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63164. */
  63165. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63166. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63167. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63168. if (isCube === void 0) { isCube = false; }
  63169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63170. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63171. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63172. if (isMulti === void 0) { isMulti = false; }
  63173. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63174. _this.isCube = isCube;
  63175. /**
  63176. * Use this list to define the list of mesh you want to render.
  63177. */
  63178. _this.renderList = new Array();
  63179. _this.renderParticles = true;
  63180. _this.renderSprites = false;
  63181. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63182. _this.ignoreCameraViewport = false;
  63183. // Events
  63184. /**
  63185. * An event triggered when the texture is unbind.
  63186. */
  63187. _this.onBeforeBindObservable = new BABYLON.Observable();
  63188. /**
  63189. * An event triggered when the texture is unbind.
  63190. */
  63191. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63192. /**
  63193. * An event triggered before rendering the texture
  63194. */
  63195. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63196. /**
  63197. * An event triggered after rendering the texture
  63198. */
  63199. _this.onAfterRenderObservable = new BABYLON.Observable();
  63200. /**
  63201. * An event triggered after the texture clear
  63202. */
  63203. _this.onClearObservable = new BABYLON.Observable();
  63204. _this._currentRefreshId = -1;
  63205. _this._refreshRate = 1;
  63206. _this._samples = 1;
  63207. /**
  63208. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63209. * It must define where the camera used to render the texture is set
  63210. */
  63211. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63212. scene = _this.getScene();
  63213. if (!scene) {
  63214. return _this;
  63215. }
  63216. _this._engine = scene.getEngine();
  63217. _this.name = name;
  63218. _this.isRenderTarget = true;
  63219. _this._initialSizeParameter = size;
  63220. _this._processSizeParameter(size);
  63221. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63222. });
  63223. _this._generateMipMaps = generateMipMaps ? true : false;
  63224. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63225. // Rendering groups
  63226. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63227. if (isMulti) {
  63228. return _this;
  63229. }
  63230. _this._renderTargetOptions = {
  63231. generateMipMaps: generateMipMaps,
  63232. type: type,
  63233. samplingMode: samplingMode,
  63234. generateDepthBuffer: generateDepthBuffer,
  63235. generateStencilBuffer: generateStencilBuffer
  63236. };
  63237. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63238. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63239. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63240. }
  63241. if (isCube) {
  63242. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63243. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63244. _this._textureMatrix = BABYLON.Matrix.Identity();
  63245. }
  63246. else {
  63247. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63248. }
  63249. return _this;
  63250. }
  63251. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63252. get: function () {
  63253. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63254. },
  63255. enumerable: true,
  63256. configurable: true
  63257. });
  63258. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63259. get: function () {
  63260. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63261. },
  63262. enumerable: true,
  63263. configurable: true
  63264. });
  63265. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63266. get: function () {
  63267. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63268. },
  63269. enumerable: true,
  63270. configurable: true
  63271. });
  63272. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63273. set: function (callback) {
  63274. if (this._onAfterUnbindObserver) {
  63275. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63276. }
  63277. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63278. },
  63279. enumerable: true,
  63280. configurable: true
  63281. });
  63282. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63283. set: function (callback) {
  63284. if (this._onBeforeRenderObserver) {
  63285. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63286. }
  63287. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63293. set: function (callback) {
  63294. if (this._onAfterRenderObserver) {
  63295. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63296. }
  63297. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63298. },
  63299. enumerable: true,
  63300. configurable: true
  63301. });
  63302. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63303. set: function (callback) {
  63304. if (this._onClearObserver) {
  63305. this.onClearObservable.remove(this._onClearObserver);
  63306. }
  63307. this._onClearObserver = this.onClearObservable.add(callback);
  63308. },
  63309. enumerable: true,
  63310. configurable: true
  63311. });
  63312. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63313. get: function () {
  63314. return this._renderTargetOptions;
  63315. },
  63316. enumerable: true,
  63317. configurable: true
  63318. });
  63319. RenderTargetTexture.prototype._onRatioRescale = function () {
  63320. if (this._sizeRatio) {
  63321. this.resize(this._initialSizeParameter);
  63322. }
  63323. };
  63324. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63325. get: function () {
  63326. return this._boundingBoxSize;
  63327. },
  63328. /**
  63329. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63330. * When defined, the cubemap will switch to local mode
  63331. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63332. * @example https://www.babylonjs-playground.com/#RNASML
  63333. */
  63334. set: function (value) {
  63335. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63336. return;
  63337. }
  63338. this._boundingBoxSize = value;
  63339. var scene = this.getScene();
  63340. if (scene) {
  63341. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63342. }
  63343. },
  63344. enumerable: true,
  63345. configurable: true
  63346. });
  63347. /**
  63348. * Creates a depth stencil texture.
  63349. * This is only available in WebGL 2 or with the depth texture extension available.
  63350. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63351. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63352. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63353. */
  63354. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63355. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63356. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63357. if (generateStencil === void 0) { generateStencil = false; }
  63358. if (!this.getScene()) {
  63359. return;
  63360. }
  63361. var engine = this.getScene().getEngine();
  63362. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63363. bilinearFiltering: bilinearFiltering,
  63364. comparisonFunction: comparisonFunction,
  63365. generateStencil: generateStencil,
  63366. isCube: this.isCube
  63367. });
  63368. engine.setFrameBufferDepthStencilTexture(this);
  63369. };
  63370. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63371. if (size.ratio) {
  63372. this._sizeRatio = size.ratio;
  63373. this._size = {
  63374. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63375. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63376. };
  63377. }
  63378. else {
  63379. this._size = size;
  63380. }
  63381. };
  63382. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63383. get: function () {
  63384. return this._samples;
  63385. },
  63386. set: function (value) {
  63387. if (this._samples === value) {
  63388. return;
  63389. }
  63390. var scene = this.getScene();
  63391. if (!scene) {
  63392. return;
  63393. }
  63394. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63395. },
  63396. enumerable: true,
  63397. configurable: true
  63398. });
  63399. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63400. this._currentRefreshId = -1;
  63401. };
  63402. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63403. get: function () {
  63404. return this._refreshRate;
  63405. },
  63406. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63407. set: function (value) {
  63408. this._refreshRate = value;
  63409. this.resetRefreshCounter();
  63410. },
  63411. enumerable: true,
  63412. configurable: true
  63413. });
  63414. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63415. if (!this._postProcessManager) {
  63416. var scene = this.getScene();
  63417. if (!scene) {
  63418. return;
  63419. }
  63420. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63421. this._postProcesses = new Array();
  63422. }
  63423. this._postProcesses.push(postProcess);
  63424. this._postProcesses[0].autoClear = false;
  63425. };
  63426. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63427. if (!this._postProcesses) {
  63428. return;
  63429. }
  63430. if (dispose) {
  63431. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63432. var postProcess = _a[_i];
  63433. postProcess.dispose();
  63434. }
  63435. }
  63436. this._postProcesses = [];
  63437. };
  63438. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63439. if (!this._postProcesses) {
  63440. return;
  63441. }
  63442. var index = this._postProcesses.indexOf(postProcess);
  63443. if (index === -1) {
  63444. return;
  63445. }
  63446. this._postProcesses.splice(index, 1);
  63447. if (this._postProcesses.length > 0) {
  63448. this._postProcesses[0].autoClear = false;
  63449. }
  63450. };
  63451. RenderTargetTexture.prototype._shouldRender = function () {
  63452. if (this._currentRefreshId === -1) { // At least render once
  63453. this._currentRefreshId = 1;
  63454. return true;
  63455. }
  63456. if (this.refreshRate === this._currentRefreshId) {
  63457. this._currentRefreshId = 1;
  63458. return true;
  63459. }
  63460. this._currentRefreshId++;
  63461. return false;
  63462. };
  63463. RenderTargetTexture.prototype.getRenderSize = function () {
  63464. if (this._size.width) {
  63465. return this._size.width;
  63466. }
  63467. return this._size;
  63468. };
  63469. RenderTargetTexture.prototype.getRenderWidth = function () {
  63470. if (this._size.width) {
  63471. return this._size.width;
  63472. }
  63473. return this._size;
  63474. };
  63475. RenderTargetTexture.prototype.getRenderHeight = function () {
  63476. if (this._size.width) {
  63477. return this._size.height;
  63478. }
  63479. return this._size;
  63480. };
  63481. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63482. get: function () {
  63483. return true;
  63484. },
  63485. enumerable: true,
  63486. configurable: true
  63487. });
  63488. RenderTargetTexture.prototype.scale = function (ratio) {
  63489. var newSize = this.getRenderSize() * ratio;
  63490. this.resize(newSize);
  63491. };
  63492. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63493. if (this.isCube) {
  63494. return this._textureMatrix;
  63495. }
  63496. return _super.prototype.getReflectionTextureMatrix.call(this);
  63497. };
  63498. RenderTargetTexture.prototype.resize = function (size) {
  63499. this.releaseInternalTexture();
  63500. var scene = this.getScene();
  63501. if (!scene) {
  63502. return;
  63503. }
  63504. this._processSizeParameter(size);
  63505. if (this.isCube) {
  63506. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63507. }
  63508. else {
  63509. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63510. }
  63511. };
  63512. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63513. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63514. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63515. var scene = this.getScene();
  63516. if (!scene) {
  63517. return;
  63518. }
  63519. var engine = scene.getEngine();
  63520. if (this.useCameraPostProcesses !== undefined) {
  63521. useCameraPostProcess = this.useCameraPostProcesses;
  63522. }
  63523. if (this._waitingRenderList) {
  63524. this.renderList = [];
  63525. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63526. var id = this._waitingRenderList[index];
  63527. var mesh_1 = scene.getMeshByID(id);
  63528. if (mesh_1) {
  63529. this.renderList.push(mesh_1);
  63530. }
  63531. }
  63532. delete this._waitingRenderList;
  63533. }
  63534. // Is predicate defined?
  63535. if (this.renderListPredicate) {
  63536. if (this.renderList) {
  63537. this.renderList.splice(0); // Clear previous renderList
  63538. }
  63539. else {
  63540. this.renderList = [];
  63541. }
  63542. var scene = this.getScene();
  63543. if (!scene) {
  63544. return;
  63545. }
  63546. var sceneMeshes = scene.meshes;
  63547. for (var index = 0; index < sceneMeshes.length; index++) {
  63548. var mesh = sceneMeshes[index];
  63549. if (this.renderListPredicate(mesh)) {
  63550. this.renderList.push(mesh);
  63551. }
  63552. }
  63553. }
  63554. this.onBeforeBindObservable.notifyObservers(this);
  63555. // Set custom projection.
  63556. // Needs to be before binding to prevent changing the aspect ratio.
  63557. var camera;
  63558. if (this.activeCamera) {
  63559. camera = this.activeCamera;
  63560. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63561. if (this.activeCamera !== scene.activeCamera) {
  63562. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63563. }
  63564. }
  63565. else {
  63566. camera = scene.activeCamera;
  63567. if (camera) {
  63568. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63569. }
  63570. }
  63571. // Prepare renderingManager
  63572. this._renderingManager.reset();
  63573. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63574. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63575. var sceneRenderId = scene.getRenderId();
  63576. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63577. var mesh = currentRenderList[meshIndex];
  63578. if (mesh) {
  63579. if (!mesh.isReady(this.refreshRate === 0)) {
  63580. this.resetRefreshCounter();
  63581. continue;
  63582. }
  63583. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63584. var isMasked = void 0;
  63585. if (!this.renderList && camera) {
  63586. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63587. }
  63588. else {
  63589. isMasked = false;
  63590. }
  63591. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63592. mesh._activate(sceneRenderId);
  63593. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63594. var subMesh = mesh.subMeshes[subIndex];
  63595. scene._activeIndices.addCount(subMesh.indexCount, false);
  63596. this._renderingManager.dispatch(subMesh, mesh);
  63597. }
  63598. }
  63599. }
  63600. }
  63601. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63602. var particleSystem = scene.particleSystems[particleIndex];
  63603. var emitter = particleSystem.emitter;
  63604. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63605. continue;
  63606. }
  63607. if (currentRenderList.indexOf(emitter) >= 0) {
  63608. this._renderingManager.dispatchParticles(particleSystem);
  63609. }
  63610. }
  63611. if (this.isCube) {
  63612. for (var face = 0; face < 6; face++) {
  63613. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63614. scene.incrementRenderId();
  63615. scene.resetCachedMaterial();
  63616. }
  63617. }
  63618. else {
  63619. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63620. }
  63621. this.onAfterUnbindObservable.notifyObservers(this);
  63622. if (scene.activeCamera) {
  63623. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63624. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63625. }
  63626. engine.setViewport(scene.activeCamera.viewport);
  63627. }
  63628. scene.resetCachedMaterial();
  63629. };
  63630. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63631. var minimum = 128;
  63632. var x = renderDimension * scale;
  63633. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63634. // Ensure we don't exceed the render dimension (while staying POT)
  63635. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63636. };
  63637. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63638. var _this = this;
  63639. if (!this._texture) {
  63640. return;
  63641. }
  63642. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63643. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63644. });
  63645. };
  63646. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63647. var scene = this.getScene();
  63648. if (!scene) {
  63649. return;
  63650. }
  63651. var engine = scene.getEngine();
  63652. if (!this._texture) {
  63653. return;
  63654. }
  63655. // Bind
  63656. if (this._postProcessManager) {
  63657. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63658. }
  63659. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63660. if (this._texture) {
  63661. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63662. }
  63663. }
  63664. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63665. // Clear
  63666. if (this.onClearObservable.hasObservers()) {
  63667. this.onClearObservable.notifyObservers(engine);
  63668. }
  63669. else {
  63670. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63671. }
  63672. if (!this._doNotChangeAspectRatio) {
  63673. scene.updateTransformMatrix(true);
  63674. }
  63675. // Render
  63676. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63677. if (this._postProcessManager) {
  63678. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63679. }
  63680. else if (useCameraPostProcess) {
  63681. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63682. }
  63683. if (!this._doNotChangeAspectRatio) {
  63684. scene.updateTransformMatrix(true);
  63685. }
  63686. // Dump ?
  63687. if (dumpForDebug) {
  63688. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63689. }
  63690. // Unbind
  63691. if (!this.isCube || faceIndex === 5) {
  63692. if (this.isCube) {
  63693. if (faceIndex === 5) {
  63694. engine.generateMipMapsForCubemap(this._texture);
  63695. }
  63696. }
  63697. this.unbindFrameBuffer(engine, faceIndex);
  63698. }
  63699. else {
  63700. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63701. }
  63702. };
  63703. /**
  63704. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63705. * This allowed control for front to back rendering or reversly depending of the special needs.
  63706. *
  63707. * @param renderingGroupId The rendering group id corresponding to its index
  63708. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63709. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63710. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63711. */
  63712. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63713. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63714. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63715. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63716. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63717. };
  63718. /**
  63719. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63720. *
  63721. * @param renderingGroupId The rendering group id corresponding to its index
  63722. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63723. */
  63724. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63725. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63726. };
  63727. RenderTargetTexture.prototype.clone = function () {
  63728. var textureSize = this.getSize();
  63729. 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);
  63730. // Base texture
  63731. newTexture.hasAlpha = this.hasAlpha;
  63732. newTexture.level = this.level;
  63733. // RenderTarget Texture
  63734. newTexture.coordinatesMode = this.coordinatesMode;
  63735. if (this.renderList) {
  63736. newTexture.renderList = this.renderList.slice(0);
  63737. }
  63738. return newTexture;
  63739. };
  63740. RenderTargetTexture.prototype.serialize = function () {
  63741. if (!this.name) {
  63742. return null;
  63743. }
  63744. var serializationObject = _super.prototype.serialize.call(this);
  63745. serializationObject.renderTargetSize = this.getRenderSize();
  63746. serializationObject.renderList = [];
  63747. if (this.renderList) {
  63748. for (var index = 0; index < this.renderList.length; index++) {
  63749. serializationObject.renderList.push(this.renderList[index].id);
  63750. }
  63751. }
  63752. return serializationObject;
  63753. };
  63754. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63755. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63756. var objBuffer = this.getInternalTexture();
  63757. var scene = this.getScene();
  63758. if (objBuffer && scene) {
  63759. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63760. }
  63761. };
  63762. RenderTargetTexture.prototype.dispose = function () {
  63763. if (this._postProcessManager) {
  63764. this._postProcessManager.dispose();
  63765. this._postProcessManager = null;
  63766. }
  63767. this.clearPostProcesses(true);
  63768. if (this._resizeObserver) {
  63769. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63770. this._resizeObserver = null;
  63771. }
  63772. this.renderList = null;
  63773. // Remove from custom render targets
  63774. var scene = this.getScene();
  63775. if (!scene) {
  63776. return;
  63777. }
  63778. var index = scene.customRenderTargets.indexOf(this);
  63779. if (index >= 0) {
  63780. scene.customRenderTargets.splice(index, 1);
  63781. }
  63782. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63783. var camera = _a[_i];
  63784. index = camera.customRenderTargets.indexOf(this);
  63785. if (index >= 0) {
  63786. camera.customRenderTargets.splice(index, 1);
  63787. }
  63788. }
  63789. _super.prototype.dispose.call(this);
  63790. };
  63791. RenderTargetTexture.prototype._rebuild = function () {
  63792. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63793. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63794. }
  63795. if (this._postProcessManager) {
  63796. this._postProcessManager._rebuild();
  63797. }
  63798. };
  63799. /**
  63800. * Clear the info related to rendering groups preventing retention point in material dispose.
  63801. */
  63802. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63803. if (this._renderingManager) {
  63804. this._renderingManager.freeRenderingGroups();
  63805. }
  63806. };
  63807. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63808. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63809. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63810. return RenderTargetTexture;
  63811. }(BABYLON.Texture));
  63812. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63813. })(BABYLON || (BABYLON = {}));
  63814. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63815. var BABYLON;
  63816. (function (BABYLON) {
  63817. ;
  63818. var MultiRenderTarget = /** @class */ (function (_super) {
  63819. __extends(MultiRenderTarget, _super);
  63820. function MultiRenderTarget(name, size, count, scene, options) {
  63821. var _this = this;
  63822. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63823. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63824. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63825. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63826. _this._engine = scene.getEngine();
  63827. if (!_this.isSupported) {
  63828. _this.dispose();
  63829. return;
  63830. }
  63831. var types = [];
  63832. var samplingModes = [];
  63833. for (var i = 0; i < count; i++) {
  63834. if (options && options.types && options.types[i] !== undefined) {
  63835. types.push(options.types[i]);
  63836. }
  63837. else {
  63838. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63839. }
  63840. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63841. samplingModes.push(options.samplingModes[i]);
  63842. }
  63843. else {
  63844. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63845. }
  63846. }
  63847. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63848. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63849. _this._size = size;
  63850. _this._multiRenderTargetOptions = {
  63851. samplingModes: samplingModes,
  63852. generateMipMaps: generateMipMaps,
  63853. generateDepthBuffer: generateDepthBuffer,
  63854. generateStencilBuffer: generateStencilBuffer,
  63855. generateDepthTexture: generateDepthTexture,
  63856. types: types,
  63857. textureCount: count
  63858. };
  63859. _this._createInternalTextures();
  63860. _this._createTextures();
  63861. return _this;
  63862. }
  63863. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63864. get: function () {
  63865. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63866. },
  63867. enumerable: true,
  63868. configurable: true
  63869. });
  63870. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63871. get: function () {
  63872. return this._textures;
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63878. get: function () {
  63879. return this._textures[this._textures.length - 1];
  63880. },
  63881. enumerable: true,
  63882. configurable: true
  63883. });
  63884. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63885. set: function (wrap) {
  63886. if (this._textures) {
  63887. for (var i = 0; i < this._textures.length; i++) {
  63888. this._textures[i].wrapU = wrap;
  63889. }
  63890. }
  63891. },
  63892. enumerable: true,
  63893. configurable: true
  63894. });
  63895. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63896. set: function (wrap) {
  63897. if (this._textures) {
  63898. for (var i = 0; i < this._textures.length; i++) {
  63899. this._textures[i].wrapV = wrap;
  63900. }
  63901. }
  63902. },
  63903. enumerable: true,
  63904. configurable: true
  63905. });
  63906. MultiRenderTarget.prototype._rebuild = function () {
  63907. this.releaseInternalTextures();
  63908. this._createInternalTextures();
  63909. for (var i = 0; i < this._internalTextures.length; i++) {
  63910. var texture = this._textures[i];
  63911. texture._texture = this._internalTextures[i];
  63912. }
  63913. // Keeps references to frame buffer and stencil/depth buffer
  63914. this._texture = this._internalTextures[0];
  63915. };
  63916. MultiRenderTarget.prototype._createInternalTextures = function () {
  63917. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63918. };
  63919. MultiRenderTarget.prototype._createTextures = function () {
  63920. this._textures = [];
  63921. for (var i = 0; i < this._internalTextures.length; i++) {
  63922. var texture = new BABYLON.Texture(null, this.getScene());
  63923. texture._texture = this._internalTextures[i];
  63924. this._textures.push(texture);
  63925. }
  63926. // Keeps references to frame buffer and stencil/depth buffer
  63927. this._texture = this._internalTextures[0];
  63928. };
  63929. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63930. get: function () {
  63931. return this._samples;
  63932. },
  63933. set: function (value) {
  63934. if (this._samples === value) {
  63935. return;
  63936. }
  63937. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63938. },
  63939. enumerable: true,
  63940. configurable: true
  63941. });
  63942. MultiRenderTarget.prototype.resize = function (size) {
  63943. this.releaseInternalTextures();
  63944. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63945. this._createInternalTextures();
  63946. };
  63947. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63948. var _this = this;
  63949. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63950. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63951. });
  63952. };
  63953. MultiRenderTarget.prototype.dispose = function () {
  63954. this.releaseInternalTextures();
  63955. _super.prototype.dispose.call(this);
  63956. };
  63957. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63958. if (!this._internalTextures) {
  63959. return;
  63960. }
  63961. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63962. if (this._internalTextures[i] !== undefined) {
  63963. this._internalTextures[i].dispose();
  63964. this._internalTextures.splice(i, 1);
  63965. }
  63966. }
  63967. };
  63968. return MultiRenderTarget;
  63969. }(BABYLON.RenderTargetTexture));
  63970. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63971. })(BABYLON || (BABYLON = {}));
  63972. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63973. var BABYLON;
  63974. (function (BABYLON) {
  63975. var MirrorTexture = /** @class */ (function (_super) {
  63976. __extends(MirrorTexture, _super);
  63977. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63978. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63980. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63981. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63982. _this.scene = scene;
  63983. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63984. _this._transformMatrix = BABYLON.Matrix.Zero();
  63985. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63986. _this._adaptiveBlurKernel = 0;
  63987. _this._blurKernelX = 0;
  63988. _this._blurKernelY = 0;
  63989. _this._blurRatio = 1.0;
  63990. _this.ignoreCameraViewport = true;
  63991. _this._updateGammaSpace();
  63992. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63993. _this._updateGammaSpace;
  63994. });
  63995. _this.onBeforeRenderObservable.add(function () {
  63996. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63997. _this._savedViewMatrix = scene.getViewMatrix();
  63998. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63999. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64000. scene.clipPlane = _this.mirrorPlane;
  64001. scene.getEngine().cullBackFaces = false;
  64002. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64003. });
  64004. _this.onAfterRenderObservable.add(function () {
  64005. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64006. scene.getEngine().cullBackFaces = true;
  64007. scene._mirroredCameraPosition = null;
  64008. delete scene.clipPlane;
  64009. });
  64010. return _this;
  64011. }
  64012. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64013. get: function () {
  64014. return this._blurRatio;
  64015. },
  64016. set: function (value) {
  64017. if (this._blurRatio === value) {
  64018. return;
  64019. }
  64020. this._blurRatio = value;
  64021. this._preparePostProcesses();
  64022. },
  64023. enumerable: true,
  64024. configurable: true
  64025. });
  64026. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64027. set: function (value) {
  64028. this._adaptiveBlurKernel = value;
  64029. this._autoComputeBlurKernel();
  64030. },
  64031. enumerable: true,
  64032. configurable: true
  64033. });
  64034. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64035. set: function (value) {
  64036. this.blurKernelX = value;
  64037. this.blurKernelY = value;
  64038. },
  64039. enumerable: true,
  64040. configurable: true
  64041. });
  64042. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64043. get: function () {
  64044. return this._blurKernelX;
  64045. },
  64046. set: function (value) {
  64047. if (this._blurKernelX === value) {
  64048. return;
  64049. }
  64050. this._blurKernelX = value;
  64051. this._preparePostProcesses();
  64052. },
  64053. enumerable: true,
  64054. configurable: true
  64055. });
  64056. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64057. get: function () {
  64058. return this._blurKernelY;
  64059. },
  64060. set: function (value) {
  64061. if (this._blurKernelY === value) {
  64062. return;
  64063. }
  64064. this._blurKernelY = value;
  64065. this._preparePostProcesses();
  64066. },
  64067. enumerable: true,
  64068. configurable: true
  64069. });
  64070. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64071. var engine = this.getScene().getEngine();
  64072. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64073. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64074. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64075. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64076. };
  64077. MirrorTexture.prototype._onRatioRescale = function () {
  64078. if (this._sizeRatio) {
  64079. this.resize(this._initialSizeParameter);
  64080. if (!this._adaptiveBlurKernel) {
  64081. this._preparePostProcesses();
  64082. }
  64083. }
  64084. if (this._adaptiveBlurKernel) {
  64085. this._autoComputeBlurKernel();
  64086. }
  64087. };
  64088. MirrorTexture.prototype._updateGammaSpace = function () {
  64089. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64090. };
  64091. MirrorTexture.prototype._preparePostProcesses = function () {
  64092. this.clearPostProcesses(true);
  64093. if (this._blurKernelX && this._blurKernelY) {
  64094. var engine = this.getScene().getEngine();
  64095. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64096. 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);
  64097. this._blurX.autoClear = false;
  64098. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64099. this._blurX.inputTexture = this._texture;
  64100. }
  64101. else {
  64102. this._blurX.alwaysForcePOT = true;
  64103. }
  64104. 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);
  64105. this._blurY.autoClear = false;
  64106. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64107. this.addPostProcess(this._blurX);
  64108. this.addPostProcess(this._blurY);
  64109. }
  64110. else {
  64111. if (this._blurY) {
  64112. this.removePostProcess(this._blurY);
  64113. this._blurY.dispose();
  64114. this._blurY = null;
  64115. }
  64116. if (this._blurX) {
  64117. this.removePostProcess(this._blurX);
  64118. this._blurX.dispose();
  64119. this._blurX = null;
  64120. }
  64121. }
  64122. };
  64123. MirrorTexture.prototype.clone = function () {
  64124. var scene = this.getScene();
  64125. if (!scene) {
  64126. return this;
  64127. }
  64128. var textureSize = this.getSize();
  64129. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64130. // Base texture
  64131. newTexture.hasAlpha = this.hasAlpha;
  64132. newTexture.level = this.level;
  64133. // Mirror Texture
  64134. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64135. if (this.renderList) {
  64136. newTexture.renderList = this.renderList.slice(0);
  64137. }
  64138. return newTexture;
  64139. };
  64140. MirrorTexture.prototype.serialize = function () {
  64141. if (!this.name) {
  64142. return null;
  64143. }
  64144. var serializationObject = _super.prototype.serialize.call(this);
  64145. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64146. return serializationObject;
  64147. };
  64148. MirrorTexture.prototype.dispose = function () {
  64149. _super.prototype.dispose.call(this);
  64150. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64151. };
  64152. return MirrorTexture;
  64153. }(BABYLON.RenderTargetTexture));
  64154. BABYLON.MirrorTexture = MirrorTexture;
  64155. })(BABYLON || (BABYLON = {}));
  64156. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64157. var BABYLON;
  64158. (function (BABYLON) {
  64159. /**
  64160. * Creates a refraction texture used by refraction channel of the standard material.
  64161. * @param name the texture name
  64162. * @param size size of the underlying texture
  64163. * @param scene root scene
  64164. */
  64165. var RefractionTexture = /** @class */ (function (_super) {
  64166. __extends(RefractionTexture, _super);
  64167. function RefractionTexture(name, size, scene, generateMipMaps) {
  64168. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64169. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64170. _this.depth = 2.0;
  64171. _this.onBeforeRenderObservable.add(function () {
  64172. scene.clipPlane = _this.refractionPlane;
  64173. });
  64174. _this.onAfterRenderObservable.add(function () {
  64175. delete scene.clipPlane;
  64176. });
  64177. return _this;
  64178. }
  64179. RefractionTexture.prototype.clone = function () {
  64180. var scene = this.getScene();
  64181. if (!scene) {
  64182. return this;
  64183. }
  64184. var textureSize = this.getSize();
  64185. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64186. // Base texture
  64187. newTexture.hasAlpha = this.hasAlpha;
  64188. newTexture.level = this.level;
  64189. // Refraction Texture
  64190. newTexture.refractionPlane = this.refractionPlane.clone();
  64191. if (this.renderList) {
  64192. newTexture.renderList = this.renderList.slice(0);
  64193. }
  64194. newTexture.depth = this.depth;
  64195. return newTexture;
  64196. };
  64197. RefractionTexture.prototype.serialize = function () {
  64198. if (!this.name) {
  64199. return null;
  64200. }
  64201. var serializationObject = _super.prototype.serialize.call(this);
  64202. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64203. serializationObject.depth = this.depth;
  64204. return serializationObject;
  64205. };
  64206. return RefractionTexture;
  64207. }(BABYLON.RenderTargetTexture));
  64208. BABYLON.RefractionTexture = RefractionTexture;
  64209. })(BABYLON || (BABYLON = {}));
  64210. //# sourceMappingURL=babylon.refractionTexture.js.map
  64211. var BABYLON;
  64212. (function (BABYLON) {
  64213. /**
  64214. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64215. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64216. */
  64217. var DynamicTexture = /** @class */ (function (_super) {
  64218. __extends(DynamicTexture, _super);
  64219. /**
  64220. * Creates a {BABYLON.DynamicTexture}
  64221. * @param name defines the name of the texture
  64222. * @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
  64223. * @param scene defines the scene where you want the texture
  64224. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64225. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64226. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64227. */
  64228. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64229. if (scene === void 0) { scene = null; }
  64230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64231. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64232. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64233. _this.name = name;
  64234. _this._engine = _this.getScene().getEngine();
  64235. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64236. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64237. _this._generateMipMaps = generateMipMaps;
  64238. if (options.getContext) {
  64239. _this._canvas = options;
  64240. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64241. }
  64242. else {
  64243. _this._canvas = document.createElement("canvas");
  64244. if (options.width || options.width === 0) {
  64245. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64246. }
  64247. else {
  64248. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64249. }
  64250. }
  64251. var textureSize = _this.getSize();
  64252. _this._canvas.width = textureSize.width;
  64253. _this._canvas.height = textureSize.height;
  64254. _this._context = _this._canvas.getContext("2d");
  64255. return _this;
  64256. }
  64257. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64258. /**
  64259. * Gets the current state of canRescale
  64260. */
  64261. get: function () {
  64262. return true;
  64263. },
  64264. enumerable: true,
  64265. configurable: true
  64266. });
  64267. DynamicTexture.prototype._recreate = function (textureSize) {
  64268. this._canvas.width = textureSize.width;
  64269. this._canvas.height = textureSize.height;
  64270. this.releaseInternalTexture();
  64271. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64272. };
  64273. /**
  64274. * Scales the texture
  64275. * @param ratio the scale factor to apply to both width and height
  64276. */
  64277. DynamicTexture.prototype.scale = function (ratio) {
  64278. var textureSize = this.getSize();
  64279. textureSize.width *= ratio;
  64280. textureSize.height *= ratio;
  64281. this._recreate(textureSize);
  64282. };
  64283. /**
  64284. * Resizes the texture
  64285. * @param width the new width
  64286. * @param height the new height
  64287. */
  64288. DynamicTexture.prototype.scaleTo = function (width, height) {
  64289. var textureSize = this.getSize();
  64290. textureSize.width = width;
  64291. textureSize.height = height;
  64292. this._recreate(textureSize);
  64293. };
  64294. /**
  64295. * Gets the context of the canvas used by the texture
  64296. * @returns the canvas context of the dynamic texture
  64297. */
  64298. DynamicTexture.prototype.getContext = function () {
  64299. return this._context;
  64300. };
  64301. /**
  64302. * Clears the texture
  64303. */
  64304. DynamicTexture.prototype.clear = function () {
  64305. var size = this.getSize();
  64306. this._context.fillRect(0, 0, size.width, size.height);
  64307. };
  64308. /**
  64309. * Updates the texture
  64310. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64311. */
  64312. DynamicTexture.prototype.update = function (invertY) {
  64313. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64314. };
  64315. /**
  64316. * Draws text onto the texture
  64317. * @param text defines the text to be drawn
  64318. * @param x defines the placement of the text from the left
  64319. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64320. * @param font defines the font to be used with font-style, font-size, font-name
  64321. * @param color defines the color used for the text
  64322. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64323. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64324. * @param update defines whether texture is immediately update (default is true)
  64325. */
  64326. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64327. if (update === void 0) { update = true; }
  64328. var size = this.getSize();
  64329. if (clearColor) {
  64330. this._context.fillStyle = clearColor;
  64331. this._context.fillRect(0, 0, size.width, size.height);
  64332. }
  64333. this._context.font = font;
  64334. if (x === null || x === undefined) {
  64335. var textSize = this._context.measureText(text);
  64336. x = (size.width - textSize.width) / 2;
  64337. }
  64338. if (y === null || y === undefined) {
  64339. var fontSize = parseInt((font.replace(/\D/g, '')));
  64340. y = (size.height / 2) + (fontSize / 3.65);
  64341. }
  64342. this._context.fillStyle = color;
  64343. this._context.fillText(text, x, y);
  64344. if (update) {
  64345. this.update(invertY);
  64346. }
  64347. };
  64348. /**
  64349. * Clones the texture
  64350. * @returns the clone of the texture.
  64351. */
  64352. DynamicTexture.prototype.clone = function () {
  64353. var scene = this.getScene();
  64354. if (!scene) {
  64355. return this;
  64356. }
  64357. var textureSize = this.getSize();
  64358. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64359. // Base texture
  64360. newTexture.hasAlpha = this.hasAlpha;
  64361. newTexture.level = this.level;
  64362. // Dynamic Texture
  64363. newTexture.wrapU = this.wrapU;
  64364. newTexture.wrapV = this.wrapV;
  64365. return newTexture;
  64366. };
  64367. /** @hidden */
  64368. DynamicTexture.prototype._rebuild = function () {
  64369. this.update();
  64370. };
  64371. return DynamicTexture;
  64372. }(BABYLON.Texture));
  64373. BABYLON.DynamicTexture = DynamicTexture;
  64374. })(BABYLON || (BABYLON = {}));
  64375. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64376. var BABYLON;
  64377. (function (BABYLON) {
  64378. var VideoTexture = /** @class */ (function (_super) {
  64379. __extends(VideoTexture, _super);
  64380. /**
  64381. * Creates a video texture.
  64382. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64383. * @param {string | null} name optional name, will detect from video source, if not defined
  64384. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64385. * @param {BABYLON.Scene} scene is obviously the current scene.
  64386. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64387. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64388. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64389. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64390. */
  64391. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64392. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64393. if (invertY === void 0) { invertY = false; }
  64394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64395. if (settings === void 0) { settings = {
  64396. autoPlay: true,
  64397. loop: true,
  64398. autoUpdateTexture: true,
  64399. }; }
  64400. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64401. _this._stillImageCaptured = false;
  64402. _this._createInternalTexture = function () {
  64403. if (_this._texture != null) {
  64404. return;
  64405. }
  64406. if (!_this._engine.needPOTTextures ||
  64407. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64408. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64409. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64410. }
  64411. else {
  64412. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64413. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64414. _this._generateMipMaps = false;
  64415. }
  64416. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64417. if (!_this.video.autoplay) {
  64418. var oldHandler_1 = _this.video.onplaying;
  64419. _this.video.onplaying = function () {
  64420. _this.video.onplaying = oldHandler_1;
  64421. _this._texture.isReady = true;
  64422. _this._updateInternalTexture();
  64423. _this.video.pause();
  64424. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64425. _this.onLoadObservable.notifyObservers(_this);
  64426. }
  64427. };
  64428. _this.video.play();
  64429. }
  64430. else {
  64431. _this._texture.isReady = true;
  64432. _this._updateInternalTexture();
  64433. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64434. _this.onLoadObservable.notifyObservers(_this);
  64435. }
  64436. }
  64437. };
  64438. _this.reset = function () {
  64439. if (_this._texture == null) {
  64440. return;
  64441. }
  64442. _this._texture.dispose();
  64443. _this._texture = null;
  64444. };
  64445. _this._updateInternalTexture = function (e) {
  64446. if (_this._texture == null || !_this._texture.isReady) {
  64447. return;
  64448. }
  64449. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64450. return;
  64451. }
  64452. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64453. };
  64454. _this._engine = _this.getScene().getEngine();
  64455. _this._generateMipMaps = generateMipMaps;
  64456. _this._samplingMode = samplingMode;
  64457. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64458. _this.name = name || _this._getName(src);
  64459. _this.video = _this._getVideo(src);
  64460. if (settings.autoPlay !== undefined) {
  64461. _this.video.autoplay = settings.autoPlay;
  64462. }
  64463. if (settings.loop !== undefined) {
  64464. _this.video.loop = settings.loop;
  64465. }
  64466. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64467. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64468. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64469. _this.video.addEventListener("emptied", _this.reset);
  64470. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64471. _this._createInternalTexture();
  64472. }
  64473. return _this;
  64474. }
  64475. VideoTexture.prototype._getName = function (src) {
  64476. if (src instanceof HTMLVideoElement) {
  64477. return src.currentSrc;
  64478. }
  64479. if (typeof src === "object") {
  64480. return src.toString();
  64481. }
  64482. return src;
  64483. };
  64484. ;
  64485. VideoTexture.prototype._getVideo = function (src) {
  64486. if (src instanceof HTMLVideoElement) {
  64487. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64488. return src;
  64489. }
  64490. var video = document.createElement("video");
  64491. if (typeof src === "string") {
  64492. BABYLON.Tools.SetCorsBehavior(src, video);
  64493. video.src = src;
  64494. }
  64495. else {
  64496. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64497. src.forEach(function (url) {
  64498. var source = document.createElement("source");
  64499. source.src = url;
  64500. video.appendChild(source);
  64501. });
  64502. }
  64503. return video;
  64504. };
  64505. ;
  64506. /**
  64507. * Internal method to initiate `update`.
  64508. */
  64509. VideoTexture.prototype._rebuild = function () {
  64510. this.update();
  64511. };
  64512. /**
  64513. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64514. */
  64515. VideoTexture.prototype.update = function () {
  64516. if (!this.autoUpdateTexture) {
  64517. // Expecting user to call `updateTexture` manually
  64518. return;
  64519. }
  64520. this.updateTexture(true);
  64521. };
  64522. /**
  64523. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64524. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64525. */
  64526. VideoTexture.prototype.updateTexture = function (isVisible) {
  64527. if (!isVisible) {
  64528. return;
  64529. }
  64530. if (this.video.paused && this._stillImageCaptured) {
  64531. return;
  64532. }
  64533. this._stillImageCaptured = true;
  64534. this._updateInternalTexture();
  64535. };
  64536. /**
  64537. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64538. * @param url New url.
  64539. */
  64540. VideoTexture.prototype.updateURL = function (url) {
  64541. this.video.src = url;
  64542. };
  64543. VideoTexture.prototype.dispose = function () {
  64544. _super.prototype.dispose.call(this);
  64545. this.video.removeEventListener("canplay", this._createInternalTexture);
  64546. this.video.removeEventListener("paused", this._updateInternalTexture);
  64547. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64548. this.video.removeEventListener("emptied", this.reset);
  64549. this.video.pause();
  64550. };
  64551. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64552. var video = document.createElement("video");
  64553. var constraintsDeviceId;
  64554. if (constraints && constraints.deviceId) {
  64555. constraintsDeviceId = {
  64556. exact: constraints.deviceId,
  64557. };
  64558. }
  64559. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64560. if (navigator.mediaDevices) {
  64561. navigator.mediaDevices.getUserMedia({ video: constraints })
  64562. .then(function (stream) {
  64563. if (video.mozSrcObject !== undefined) {
  64564. // hack for Firefox < 19
  64565. video.mozSrcObject = stream;
  64566. }
  64567. else {
  64568. video.srcObject = stream;
  64569. }
  64570. var onPlaying = function () {
  64571. if (onReady) {
  64572. onReady(new VideoTexture("video", video, scene, true, true));
  64573. }
  64574. video.removeEventListener("playing", onPlaying);
  64575. };
  64576. video.addEventListener("playing", onPlaying);
  64577. video.play();
  64578. })
  64579. .catch(function (err) {
  64580. BABYLON.Tools.Error(err.name);
  64581. });
  64582. }
  64583. else {
  64584. navigator.getUserMedia =
  64585. navigator.getUserMedia ||
  64586. navigator.webkitGetUserMedia ||
  64587. navigator.mozGetUserMedia ||
  64588. navigator.msGetUserMedia;
  64589. if (navigator.getUserMedia) {
  64590. navigator.getUserMedia({
  64591. video: {
  64592. deviceId: constraintsDeviceId,
  64593. width: {
  64594. min: (constraints && constraints.minWidth) || 256,
  64595. max: (constraints && constraints.maxWidth) || 640,
  64596. },
  64597. height: {
  64598. min: (constraints && constraints.minHeight) || 256,
  64599. max: (constraints && constraints.maxHeight) || 480,
  64600. },
  64601. },
  64602. }, function (stream) {
  64603. if (video.mozSrcObject !== undefined) {
  64604. // hack for Firefox < 19
  64605. video.mozSrcObject = stream;
  64606. }
  64607. else {
  64608. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64609. }
  64610. video.play();
  64611. if (onReady) {
  64612. onReady(new VideoTexture("video", video, scene, true, true));
  64613. }
  64614. }, function (e) {
  64615. BABYLON.Tools.Error(e.name);
  64616. });
  64617. }
  64618. }
  64619. };
  64620. return VideoTexture;
  64621. }(BABYLON.Texture));
  64622. BABYLON.VideoTexture = VideoTexture;
  64623. })(BABYLON || (BABYLON = {}));
  64624. //# sourceMappingURL=babylon.videoTexture.js.map
  64625. var BABYLON;
  64626. (function (BABYLON) {
  64627. var RawTexture = /** @class */ (function (_super) {
  64628. __extends(RawTexture, _super);
  64629. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64631. if (invertY === void 0) { invertY = false; }
  64632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64633. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64634. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64635. _this.format = format;
  64636. _this._engine = scene.getEngine();
  64637. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64638. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64639. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64640. return _this;
  64641. }
  64642. RawTexture.prototype.update = function (data) {
  64643. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64644. };
  64645. // Statics
  64646. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64648. if (invertY === void 0) { invertY = false; }
  64649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64650. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64651. };
  64652. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64653. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64654. if (invertY === void 0) { invertY = false; }
  64655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64656. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64657. };
  64658. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64659. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64660. if (invertY === void 0) { invertY = false; }
  64661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64662. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64663. };
  64664. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64666. if (invertY === void 0) { invertY = false; }
  64667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64668. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64669. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64670. };
  64671. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64672. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64673. if (invertY === void 0) { invertY = false; }
  64674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64675. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64676. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64677. };
  64678. return RawTexture;
  64679. }(BABYLON.Texture));
  64680. BABYLON.RawTexture = RawTexture;
  64681. })(BABYLON || (BABYLON = {}));
  64682. //# sourceMappingURL=babylon.rawTexture.js.map
  64683. var BABYLON;
  64684. (function (BABYLON) {
  64685. /**
  64686. * Class used to store 3D textures containing user data
  64687. */
  64688. var RawTexture3D = /** @class */ (function (_super) {
  64689. __extends(RawTexture3D, _super);
  64690. /**
  64691. * Create a new RawTexture3D
  64692. * @param data defines the data of the texture
  64693. * @param width defines the width of the texture
  64694. * @param height defines the height of the texture
  64695. * @param depth defines the depth of the texture
  64696. * @param format defines the texture format to use
  64697. * @param scene defines the hosting scene
  64698. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64699. * @param invertY defines if texture must be stored with Y axis inverted
  64700. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64701. */
  64702. function RawTexture3D(data, width, height, depth,
  64703. /** Gets or sets the texture format to use*/
  64704. format, scene, generateMipMaps, invertY, samplingMode) {
  64705. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64706. if (invertY === void 0) { invertY = false; }
  64707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64708. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64709. _this.format = format;
  64710. _this._engine = scene.getEngine();
  64711. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64712. _this.is3D = true;
  64713. return _this;
  64714. }
  64715. /**
  64716. * Update the texture with new data
  64717. * @param data defines the data to store in the texture
  64718. */
  64719. RawTexture3D.prototype.update = function (data) {
  64720. if (!this._texture) {
  64721. return;
  64722. }
  64723. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64724. };
  64725. return RawTexture3D;
  64726. }(BABYLON.Texture));
  64727. BABYLON.RawTexture3D = RawTexture3D;
  64728. })(BABYLON || (BABYLON = {}));
  64729. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64730. var BABYLON;
  64731. (function (BABYLON) {
  64732. /**
  64733. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64734. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64735. */
  64736. var PostProcess = /** @class */ (function () {
  64737. /**
  64738. * Creates a new instance PostProcess
  64739. * @param name The name of the PostProcess.
  64740. * @param fragmentUrl The url of the fragment shader to be used.
  64741. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64742. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64743. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64744. * @param camera The camera to apply the render pass to.
  64745. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64746. * @param engine The engine which the post process will be applied. (default: current engine)
  64747. * @param reusable If the post process can be reused on the same frame. (default: false)
  64748. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64749. * @param textureType Type of textures used when performing the post process. (default: 0)
  64750. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64751. * @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
  64752. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64753. */
  64754. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64756. if (defines === void 0) { defines = null; }
  64757. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64758. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64759. if (blockCompilation === void 0) { blockCompilation = false; }
  64760. this.name = name;
  64761. /**
  64762. * Width of the texture to apply the post process on
  64763. */
  64764. this.width = -1;
  64765. /**
  64766. * Height of the texture to apply the post process on
  64767. */
  64768. this.height = -1;
  64769. /**
  64770. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64771. */
  64772. this._outputTexture = null;
  64773. /**
  64774. * If the buffer needs to be cleared before applying the post process. (default: true)
  64775. * Should be set to false if shader will overwrite all previous pixels.
  64776. */
  64777. this.autoClear = true;
  64778. /**
  64779. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64780. */
  64781. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64782. /**
  64783. * Animations to be used for the post processing
  64784. */
  64785. this.animations = new Array();
  64786. /**
  64787. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64788. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64789. */
  64790. this.enablePixelPerfectMode = false;
  64791. /**
  64792. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64793. */
  64794. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64795. /**
  64796. * Force textures to be a power of two (default: false)
  64797. */
  64798. this.alwaysForcePOT = false;
  64799. /**
  64800. * Number of sample textures (default: 1)
  64801. */
  64802. this.samples = 1;
  64803. /**
  64804. * Modify the scale of the post process to be the same as the viewport (default: false)
  64805. */
  64806. this.adaptScaleToCurrentViewport = false;
  64807. this._reusable = false;
  64808. /**
  64809. * Smart array of input and output textures for the post process.
  64810. */
  64811. this._textures = new BABYLON.SmartArray(2);
  64812. /**
  64813. * The index in _textures that corresponds to the output texture.
  64814. */
  64815. this._currentRenderTextureInd = 0;
  64816. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64817. this._texelSize = BABYLON.Vector2.Zero();
  64818. // Events
  64819. /**
  64820. * An event triggered when the postprocess is activated.
  64821. */
  64822. this.onActivateObservable = new BABYLON.Observable();
  64823. /**
  64824. * An event triggered when the postprocess changes its size.
  64825. */
  64826. this.onSizeChangedObservable = new BABYLON.Observable();
  64827. /**
  64828. * An event triggered when the postprocess applies its effect.
  64829. */
  64830. this.onApplyObservable = new BABYLON.Observable();
  64831. /**
  64832. * An event triggered before rendering the postprocess
  64833. */
  64834. this.onBeforeRenderObservable = new BABYLON.Observable();
  64835. /**
  64836. * An event triggered after rendering the postprocess
  64837. */
  64838. this.onAfterRenderObservable = new BABYLON.Observable();
  64839. if (camera != null) {
  64840. this._camera = camera;
  64841. this._scene = camera.getScene();
  64842. camera.attachPostProcess(this);
  64843. this._engine = this._scene.getEngine();
  64844. this._scene.postProcesses.push(this);
  64845. }
  64846. else if (engine) {
  64847. this._engine = engine;
  64848. this._engine.postProcesses.push(this);
  64849. }
  64850. this._options = options;
  64851. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64852. this._reusable = reusable || false;
  64853. this._textureType = textureType;
  64854. this._samplers = samplers || [];
  64855. this._samplers.push("textureSampler");
  64856. this._fragmentUrl = fragmentUrl;
  64857. this._vertexUrl = vertexUrl;
  64858. this._parameters = parameters || [];
  64859. this._parameters.push("scale");
  64860. this._indexParameters = indexParameters;
  64861. if (!blockCompilation) {
  64862. this.updateEffect(defines);
  64863. }
  64864. }
  64865. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64866. /**
  64867. * A function that is added to the onActivateObservable
  64868. */
  64869. set: function (callback) {
  64870. if (this._onActivateObserver) {
  64871. this.onActivateObservable.remove(this._onActivateObserver);
  64872. }
  64873. if (callback) {
  64874. this._onActivateObserver = this.onActivateObservable.add(callback);
  64875. }
  64876. },
  64877. enumerable: true,
  64878. configurable: true
  64879. });
  64880. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64881. /**
  64882. * A function that is added to the onSizeChangedObservable
  64883. */
  64884. set: function (callback) {
  64885. if (this._onSizeChangedObserver) {
  64886. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64887. }
  64888. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64889. },
  64890. enumerable: true,
  64891. configurable: true
  64892. });
  64893. Object.defineProperty(PostProcess.prototype, "onApply", {
  64894. /**
  64895. * A function that is added to the onApplyObservable
  64896. */
  64897. set: function (callback) {
  64898. if (this._onApplyObserver) {
  64899. this.onApplyObservable.remove(this._onApplyObserver);
  64900. }
  64901. this._onApplyObserver = this.onApplyObservable.add(callback);
  64902. },
  64903. enumerable: true,
  64904. configurable: true
  64905. });
  64906. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64907. /**
  64908. * A function that is added to the onBeforeRenderObservable
  64909. */
  64910. set: function (callback) {
  64911. if (this._onBeforeRenderObserver) {
  64912. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64913. }
  64914. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64915. },
  64916. enumerable: true,
  64917. configurable: true
  64918. });
  64919. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64920. /**
  64921. * A function that is added to the onAfterRenderObservable
  64922. */
  64923. set: function (callback) {
  64924. if (this._onAfterRenderObserver) {
  64925. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64926. }
  64927. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64928. },
  64929. enumerable: true,
  64930. configurable: true
  64931. });
  64932. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64933. /**
  64934. * 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
  64935. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64936. */
  64937. get: function () {
  64938. return this._textures.data[this._currentRenderTextureInd];
  64939. },
  64940. set: function (value) {
  64941. this._forcedOutputTexture = value;
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. /**
  64947. * Gets the camera which post process is applied to.
  64948. * @returns The camera the post process is applied to.
  64949. */
  64950. PostProcess.prototype.getCamera = function () {
  64951. return this._camera;
  64952. };
  64953. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64954. /**
  64955. * Gets the texel size of the postprocess.
  64956. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64957. */
  64958. get: function () {
  64959. if (this._shareOutputWithPostProcess) {
  64960. return this._shareOutputWithPostProcess.texelSize;
  64961. }
  64962. if (this._forcedOutputTexture) {
  64963. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64964. }
  64965. return this._texelSize;
  64966. },
  64967. enumerable: true,
  64968. configurable: true
  64969. });
  64970. /**
  64971. * Gets the engine which this post process belongs to.
  64972. * @returns The engine the post process was enabled with.
  64973. */
  64974. PostProcess.prototype.getEngine = function () {
  64975. return this._engine;
  64976. };
  64977. /**
  64978. * The effect that is created when initializing the post process.
  64979. * @returns The created effect corrisponding the the postprocess.
  64980. */
  64981. PostProcess.prototype.getEffect = function () {
  64982. return this._effect;
  64983. };
  64984. /**
  64985. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64986. * @param postProcess The post process to share the output with.
  64987. * @returns This post process.
  64988. */
  64989. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64990. this._disposeTextures();
  64991. this._shareOutputWithPostProcess = postProcess;
  64992. return this;
  64993. };
  64994. /**
  64995. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64996. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64997. */
  64998. PostProcess.prototype.useOwnOutput = function () {
  64999. if (this._textures.length == 0) {
  65000. this._textures = new BABYLON.SmartArray(2);
  65001. }
  65002. this._shareOutputWithPostProcess = null;
  65003. };
  65004. /**
  65005. * Updates the effect with the current post process compile time values and recompiles the shader.
  65006. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65007. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65008. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65009. * @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
  65010. * @param onCompiled Called when the shader has been compiled.
  65011. * @param onError Called if there is an error when compiling a shader.
  65012. */
  65013. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65014. if (defines === void 0) { defines = null; }
  65015. if (uniforms === void 0) { uniforms = null; }
  65016. if (samplers === void 0) { samplers = null; }
  65017. 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);
  65018. };
  65019. /**
  65020. * The post process is reusable if it can be used multiple times within one frame.
  65021. * @returns If the post process is reusable
  65022. */
  65023. PostProcess.prototype.isReusable = function () {
  65024. return this._reusable;
  65025. };
  65026. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65027. PostProcess.prototype.markTextureDirty = function () {
  65028. this.width = -1;
  65029. };
  65030. /**
  65031. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65032. * 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.
  65033. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65034. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65035. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65036. * @returns The target texture that was bound to be written to.
  65037. */
  65038. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65039. var _this = this;
  65040. if (sourceTexture === void 0) { sourceTexture = null; }
  65041. camera = camera || this._camera;
  65042. var scene = camera.getScene();
  65043. var engine = scene.getEngine();
  65044. var maxSize = engine.getCaps().maxTextureSize;
  65045. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65046. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65047. // 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
  65048. var webVRCamera = camera.parent;
  65049. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65050. requiredWidth /= 2;
  65051. }
  65052. var desiredWidth = (this._options.width || requiredWidth);
  65053. var desiredHeight = this._options.height || requiredHeight;
  65054. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65055. if (this.adaptScaleToCurrentViewport) {
  65056. var currentViewport = engine.currentViewport;
  65057. if (currentViewport) {
  65058. desiredWidth *= currentViewport.width;
  65059. desiredHeight *= currentViewport.height;
  65060. }
  65061. }
  65062. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65063. if (!this._options.width) {
  65064. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65065. }
  65066. if (!this._options.height) {
  65067. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65068. }
  65069. }
  65070. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65071. if (this._textures.length > 0) {
  65072. for (var i = 0; i < this._textures.length; i++) {
  65073. this._engine._releaseTexture(this._textures.data[i]);
  65074. }
  65075. this._textures.reset();
  65076. }
  65077. this.width = desiredWidth;
  65078. this.height = desiredHeight;
  65079. var textureSize = { width: this.width, height: this.height };
  65080. var textureOptions = {
  65081. generateMipMaps: false,
  65082. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65083. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65084. samplingMode: this.renderTargetSamplingMode,
  65085. type: this._textureType
  65086. };
  65087. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65088. if (this._reusable) {
  65089. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65090. }
  65091. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65092. this.onSizeChangedObservable.notifyObservers(this);
  65093. }
  65094. this._textures.forEach(function (texture) {
  65095. if (texture.samples !== _this.samples) {
  65096. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65097. }
  65098. });
  65099. }
  65100. var target;
  65101. if (this._shareOutputWithPostProcess) {
  65102. target = this._shareOutputWithPostProcess.inputTexture;
  65103. }
  65104. else if (this._forcedOutputTexture) {
  65105. target = this._forcedOutputTexture;
  65106. this.width = this._forcedOutputTexture.width;
  65107. this.height = this._forcedOutputTexture.height;
  65108. }
  65109. else {
  65110. target = this.inputTexture;
  65111. }
  65112. // Bind the input of this post process to be used as the output of the previous post process.
  65113. if (this.enablePixelPerfectMode) {
  65114. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65115. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65116. }
  65117. else {
  65118. this._scaleRatio.copyFromFloats(1, 1);
  65119. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65120. }
  65121. this.onActivateObservable.notifyObservers(camera);
  65122. // Clear
  65123. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65124. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65125. }
  65126. if (this._reusable) {
  65127. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65128. }
  65129. return target;
  65130. };
  65131. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65132. /**
  65133. * If the post process is supported.
  65134. */
  65135. get: function () {
  65136. return this._effect.isSupported;
  65137. },
  65138. enumerable: true,
  65139. configurable: true
  65140. });
  65141. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65142. /**
  65143. * The aspect ratio of the output texture.
  65144. */
  65145. get: function () {
  65146. if (this._shareOutputWithPostProcess) {
  65147. return this._shareOutputWithPostProcess.aspectRatio;
  65148. }
  65149. if (this._forcedOutputTexture) {
  65150. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65151. }
  65152. return this.width / this.height;
  65153. },
  65154. enumerable: true,
  65155. configurable: true
  65156. });
  65157. /**
  65158. * Get a value indicating if the post-process is ready to be used
  65159. * @returns true if the post-process is ready (shader is compiled)
  65160. */
  65161. PostProcess.prototype.isReady = function () {
  65162. return this._effect && this._effect.isReady();
  65163. };
  65164. /**
  65165. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65166. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65167. */
  65168. PostProcess.prototype.apply = function () {
  65169. // Check
  65170. if (!this._effect || !this._effect.isReady())
  65171. return null;
  65172. // States
  65173. this._engine.enableEffect(this._effect);
  65174. this._engine.setState(false);
  65175. this._engine.setDepthBuffer(false);
  65176. this._engine.setDepthWrite(false);
  65177. // Alpha
  65178. this._engine.setAlphaMode(this.alphaMode);
  65179. if (this.alphaConstants) {
  65180. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65181. }
  65182. // Bind the output texture of the preivous post process as the input to this post process.
  65183. var source;
  65184. if (this._shareOutputWithPostProcess) {
  65185. source = this._shareOutputWithPostProcess.inputTexture;
  65186. }
  65187. else if (this._forcedOutputTexture) {
  65188. source = this._forcedOutputTexture;
  65189. }
  65190. else {
  65191. source = this.inputTexture;
  65192. }
  65193. this._effect._bindTexture("textureSampler", source);
  65194. // Parameters
  65195. this._effect.setVector2("scale", this._scaleRatio);
  65196. this.onApplyObservable.notifyObservers(this._effect);
  65197. return this._effect;
  65198. };
  65199. PostProcess.prototype._disposeTextures = function () {
  65200. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65201. return;
  65202. }
  65203. if (this._textures.length > 0) {
  65204. for (var i = 0; i < this._textures.length; i++) {
  65205. this._engine._releaseTexture(this._textures.data[i]);
  65206. }
  65207. }
  65208. this._textures.dispose();
  65209. };
  65210. /**
  65211. * Disposes the post process.
  65212. * @param camera The camera to dispose the post process on.
  65213. */
  65214. PostProcess.prototype.dispose = function (camera) {
  65215. camera = camera || this._camera;
  65216. this._disposeTextures();
  65217. if (this._scene) {
  65218. var index_1 = this._scene.postProcesses.indexOf(this);
  65219. if (index_1 !== -1) {
  65220. this._scene.postProcesses.splice(index_1, 1);
  65221. }
  65222. }
  65223. else {
  65224. var index_2 = this._engine.postProcesses.indexOf(this);
  65225. if (index_2 !== -1) {
  65226. this._engine.postProcesses.splice(index_2, 1);
  65227. }
  65228. }
  65229. if (!camera) {
  65230. return;
  65231. }
  65232. camera.detachPostProcess(this);
  65233. var index = camera._postProcesses.indexOf(this);
  65234. if (index === 0 && camera._postProcesses.length > 0) {
  65235. var firstPostProcess = this._camera._getFirstPostProcess();
  65236. if (firstPostProcess) {
  65237. firstPostProcess.markTextureDirty();
  65238. }
  65239. }
  65240. this.onActivateObservable.clear();
  65241. this.onAfterRenderObservable.clear();
  65242. this.onApplyObservable.clear();
  65243. this.onBeforeRenderObservable.clear();
  65244. this.onSizeChangedObservable.clear();
  65245. };
  65246. return PostProcess;
  65247. }());
  65248. BABYLON.PostProcess = PostProcess;
  65249. })(BABYLON || (BABYLON = {}));
  65250. //# sourceMappingURL=babylon.postProcess.js.map
  65251. var BABYLON;
  65252. (function (BABYLON) {
  65253. var PassPostProcess = /** @class */ (function (_super) {
  65254. __extends(PassPostProcess, _super);
  65255. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65256. if (camera === void 0) { camera = null; }
  65257. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65258. if (blockCompilation === void 0) { blockCompilation = false; }
  65259. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65260. }
  65261. return PassPostProcess;
  65262. }(BABYLON.PostProcess));
  65263. BABYLON.PassPostProcess = PassPostProcess;
  65264. })(BABYLON || (BABYLON = {}));
  65265. //# sourceMappingURL=babylon.passPostProcess.js.map
  65266. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65267. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65268. s = arguments[i];
  65269. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65270. t[p] = s[p];
  65271. }
  65272. return t;
  65273. };
  65274. var BABYLON;
  65275. (function (BABYLON) {
  65276. /**
  65277. * Default implementation IShadowGenerator.
  65278. * This is the main object responsible of generating shadows in the framework.
  65279. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65280. */
  65281. var ShadowGenerator = /** @class */ (function () {
  65282. /**
  65283. * Creates a ShadowGenerator object.
  65284. * A ShadowGenerator is the required tool to use the shadows.
  65285. * Each light casting shadows needs to use its own ShadowGenerator.
  65286. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65287. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65288. * @param light The light object generating the shadows.
  65289. * @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.
  65290. */
  65291. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65292. this._bias = 0.00005;
  65293. this._normalBias = 0;
  65294. this._blurBoxOffset = 1;
  65295. this._blurScale = 2;
  65296. this._blurKernel = 1;
  65297. this._useKernelBlur = false;
  65298. this._filter = ShadowGenerator.FILTER_NONE;
  65299. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65300. this._contactHardeningLightSizeUVRatio = 0.1;
  65301. this._darkness = 0;
  65302. this._transparencyShadow = false;
  65303. /**
  65304. * Controls the extent to which the shadows fade out at the edge of the frustum
  65305. * Used only by directionals and spots
  65306. */
  65307. this.frustumEdgeFalloff = 0;
  65308. /**
  65309. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65310. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65311. * It might on the other hand introduce peter panning.
  65312. */
  65313. this.forceBackFacesOnly = false;
  65314. this._lightDirection = BABYLON.Vector3.Zero();
  65315. this._viewMatrix = BABYLON.Matrix.Zero();
  65316. this._projectionMatrix = BABYLON.Matrix.Zero();
  65317. this._transformMatrix = BABYLON.Matrix.Zero();
  65318. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65319. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65320. this._currentFaceIndex = 0;
  65321. this._currentFaceIndexCache = 0;
  65322. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65323. this._mapSize = mapSize;
  65324. this._light = light;
  65325. this._scene = light.getScene();
  65326. light._shadowGenerator = this;
  65327. // Texture type fallback from float to int if not supported.
  65328. var caps = this._scene.getEngine().getCaps();
  65329. if (!useFullFloatFirst) {
  65330. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65331. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65332. }
  65333. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65334. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65335. }
  65336. else {
  65337. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65338. }
  65339. }
  65340. else {
  65341. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65342. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65343. }
  65344. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65345. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65346. }
  65347. else {
  65348. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65349. }
  65350. }
  65351. this._initializeGenerator();
  65352. this._applyFilterValues();
  65353. }
  65354. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65355. /**
  65356. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65357. */
  65358. get: function () {
  65359. return this._bias;
  65360. },
  65361. /**
  65362. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65363. */
  65364. set: function (bias) {
  65365. this._bias = bias;
  65366. },
  65367. enumerable: true,
  65368. configurable: true
  65369. });
  65370. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65371. /**
  65372. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65373. */
  65374. get: function () {
  65375. return this._normalBias;
  65376. },
  65377. /**
  65378. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65379. */
  65380. set: function (normalBias) {
  65381. this._normalBias = normalBias;
  65382. },
  65383. enumerable: true,
  65384. configurable: true
  65385. });
  65386. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65387. /**
  65388. * Gets the blur box offset: offset applied during the blur pass.
  65389. * Only usefull if useKernelBlur = false
  65390. */
  65391. get: function () {
  65392. return this._blurBoxOffset;
  65393. },
  65394. /**
  65395. * Sets the blur box offset: offset applied during the blur pass.
  65396. * Only usefull if useKernelBlur = false
  65397. */
  65398. set: function (value) {
  65399. if (this._blurBoxOffset === value) {
  65400. return;
  65401. }
  65402. this._blurBoxOffset = value;
  65403. this._disposeBlurPostProcesses();
  65404. },
  65405. enumerable: true,
  65406. configurable: true
  65407. });
  65408. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65409. /**
  65410. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65411. * 2 means half of the size.
  65412. */
  65413. get: function () {
  65414. return this._blurScale;
  65415. },
  65416. /**
  65417. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65418. * 2 means half of the size.
  65419. */
  65420. set: function (value) {
  65421. if (this._blurScale === value) {
  65422. return;
  65423. }
  65424. this._blurScale = value;
  65425. this._disposeBlurPostProcesses();
  65426. },
  65427. enumerable: true,
  65428. configurable: true
  65429. });
  65430. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65431. /**
  65432. * Gets the blur kernel: kernel size of the blur pass.
  65433. * Only usefull if useKernelBlur = true
  65434. */
  65435. get: function () {
  65436. return this._blurKernel;
  65437. },
  65438. /**
  65439. * Sets the blur kernel: kernel size of the blur pass.
  65440. * Only usefull if useKernelBlur = true
  65441. */
  65442. set: function (value) {
  65443. if (this._blurKernel === value) {
  65444. return;
  65445. }
  65446. this._blurKernel = value;
  65447. this._disposeBlurPostProcesses();
  65448. },
  65449. enumerable: true,
  65450. configurable: true
  65451. });
  65452. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65453. /**
  65454. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65455. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65456. */
  65457. get: function () {
  65458. return this._useKernelBlur;
  65459. },
  65460. /**
  65461. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65462. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65463. */
  65464. set: function (value) {
  65465. if (this._useKernelBlur === value) {
  65466. return;
  65467. }
  65468. this._useKernelBlur = value;
  65469. this._disposeBlurPostProcesses();
  65470. },
  65471. enumerable: true,
  65472. configurable: true
  65473. });
  65474. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65475. /**
  65476. * Gets the depth scale used in ESM mode.
  65477. */
  65478. get: function () {
  65479. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65480. },
  65481. /**
  65482. * Sets the depth scale used in ESM mode.
  65483. * This can override the scale stored on the light.
  65484. */
  65485. set: function (value) {
  65486. this._depthScale = value;
  65487. },
  65488. enumerable: true,
  65489. configurable: true
  65490. });
  65491. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65492. /**
  65493. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65494. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65495. */
  65496. get: function () {
  65497. return this._filter;
  65498. },
  65499. /**
  65500. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65501. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65502. */
  65503. set: function (value) {
  65504. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65505. if (this._light.needCube()) {
  65506. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65507. this.useExponentialShadowMap = true;
  65508. return;
  65509. }
  65510. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65511. this.useCloseExponentialShadowMap = true;
  65512. return;
  65513. }
  65514. // PCF on cubemap would also be expensive
  65515. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65516. this.usePoissonSampling = true;
  65517. return;
  65518. }
  65519. }
  65520. // Weblg1 fallback for PCF.
  65521. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65522. if (this._scene.getEngine().webGLVersion === 1) {
  65523. this.usePoissonSampling = true;
  65524. return;
  65525. }
  65526. }
  65527. if (this._filter === value) {
  65528. return;
  65529. }
  65530. this._filter = value;
  65531. this._disposeBlurPostProcesses();
  65532. this._applyFilterValues();
  65533. this._light._markMeshesAsLightDirty();
  65534. },
  65535. enumerable: true,
  65536. configurable: true
  65537. });
  65538. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65539. /**
  65540. * Gets if the current filter is set to Poisson Sampling.
  65541. */
  65542. get: function () {
  65543. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65544. },
  65545. /**
  65546. * Sets the current filter to Poisson Sampling.
  65547. */
  65548. set: function (value) {
  65549. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65550. return;
  65551. }
  65552. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65553. },
  65554. enumerable: true,
  65555. configurable: true
  65556. });
  65557. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65558. /**
  65559. * Gets if the current filter is set to VSM.
  65560. * DEPRECATED. Should use useExponentialShadowMap instead.
  65561. */
  65562. get: function () {
  65563. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65564. return this.useExponentialShadowMap;
  65565. },
  65566. /**
  65567. * Sets the current filter is to VSM.
  65568. * DEPRECATED. Should use useExponentialShadowMap instead.
  65569. */
  65570. set: function (value) {
  65571. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65572. this.useExponentialShadowMap = value;
  65573. },
  65574. enumerable: true,
  65575. configurable: true
  65576. });
  65577. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65578. /**
  65579. * Gets if the current filter is set to blurred VSM.
  65580. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65581. */
  65582. get: function () {
  65583. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65584. return this.useBlurExponentialShadowMap;
  65585. },
  65586. /**
  65587. * Sets the current filter is to blurred VSM.
  65588. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65589. */
  65590. set: function (value) {
  65591. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65592. this.useBlurExponentialShadowMap = value;
  65593. },
  65594. enumerable: true,
  65595. configurable: true
  65596. });
  65597. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65598. /**
  65599. * Gets if the current filter is set to ESM.
  65600. */
  65601. get: function () {
  65602. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65603. },
  65604. /**
  65605. * Sets the current filter is to ESM.
  65606. */
  65607. set: function (value) {
  65608. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65609. return;
  65610. }
  65611. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65612. },
  65613. enumerable: true,
  65614. configurable: true
  65615. });
  65616. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65617. /**
  65618. * Gets if the current filter is set to filtered ESM.
  65619. */
  65620. get: function () {
  65621. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65622. },
  65623. /**
  65624. * Gets if the current filter is set to filtered ESM.
  65625. */
  65626. set: function (value) {
  65627. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65628. return;
  65629. }
  65630. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65631. },
  65632. enumerable: true,
  65633. configurable: true
  65634. });
  65635. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65636. /**
  65637. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65638. * exponential to prevent steep falloff artifacts).
  65639. */
  65640. get: function () {
  65641. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65642. },
  65643. /**
  65644. * Sets the current filter to "close ESM" (using the inverse of the
  65645. * exponential to prevent steep falloff artifacts).
  65646. */
  65647. set: function (value) {
  65648. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65649. return;
  65650. }
  65651. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65652. },
  65653. enumerable: true,
  65654. configurable: true
  65655. });
  65656. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65657. /**
  65658. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65659. * exponential to prevent steep falloff artifacts).
  65660. */
  65661. get: function () {
  65662. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65663. },
  65664. /**
  65665. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65666. * exponential to prevent steep falloff artifacts).
  65667. */
  65668. set: function (value) {
  65669. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65670. return;
  65671. }
  65672. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65673. },
  65674. enumerable: true,
  65675. configurable: true
  65676. });
  65677. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65678. /**
  65679. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65680. */
  65681. get: function () {
  65682. return this.filter === ShadowGenerator.FILTER_PCF;
  65683. },
  65684. /**
  65685. * Sets the current filter to "PCF" (percentage closer filtering).
  65686. */
  65687. set: function (value) {
  65688. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65689. return;
  65690. }
  65691. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65692. },
  65693. enumerable: true,
  65694. configurable: true
  65695. });
  65696. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65697. /**
  65698. * Gets the PCF or PCSS Quality.
  65699. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65700. */
  65701. get: function () {
  65702. return this._filteringQuality;
  65703. },
  65704. /**
  65705. * Sets the PCF or PCSS Quality.
  65706. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65707. */
  65708. set: function (filteringQuality) {
  65709. this._filteringQuality = filteringQuality;
  65710. },
  65711. enumerable: true,
  65712. configurable: true
  65713. });
  65714. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65715. /**
  65716. * Gets if the current filter is set to "PCSS" (contact hardening).
  65717. */
  65718. get: function () {
  65719. return this.filter === ShadowGenerator.FILTER_PCSS;
  65720. },
  65721. /**
  65722. * Sets the current filter to "PCSS" (contact hardening).
  65723. */
  65724. set: function (value) {
  65725. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65726. return;
  65727. }
  65728. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65729. },
  65730. enumerable: true,
  65731. configurable: true
  65732. });
  65733. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65734. /**
  65735. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65736. * Using a ratio helps keeping shape stability independently of the map size.
  65737. *
  65738. * It does not account for the light projection as it was having too much
  65739. * instability during the light setup or during light position changes.
  65740. *
  65741. * Only valid if useContactHardeningShadow is true.
  65742. */
  65743. get: function () {
  65744. return this._contactHardeningLightSizeUVRatio;
  65745. },
  65746. /**
  65747. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65748. * Using a ratio helps keeping shape stability independently of the map size.
  65749. *
  65750. * It does not account for the light projection as it was having too much
  65751. * instability during the light setup or during light position changes.
  65752. *
  65753. * Only valid if useContactHardeningShadow is true.
  65754. */
  65755. set: function (contactHardeningLightSizeUVRatio) {
  65756. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65757. },
  65758. enumerable: true,
  65759. configurable: true
  65760. });
  65761. /**
  65762. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65763. * 0 means strongest and 1 would means no shadow.
  65764. * @returns the darkness.
  65765. */
  65766. ShadowGenerator.prototype.getDarkness = function () {
  65767. return this._darkness;
  65768. };
  65769. /**
  65770. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65771. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65772. * @returns the shadow generator allowing fluent coding.
  65773. */
  65774. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65775. if (darkness >= 1.0)
  65776. this._darkness = 1.0;
  65777. else if (darkness <= 0.0)
  65778. this._darkness = 0.0;
  65779. else
  65780. this._darkness = darkness;
  65781. return this;
  65782. };
  65783. /**
  65784. * Sets the ability to have transparent shadow (boolean).
  65785. * @param transparent True if transparent else False
  65786. * @returns the shadow generator allowing fluent coding
  65787. */
  65788. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65789. this._transparencyShadow = transparent;
  65790. return this;
  65791. };
  65792. /**
  65793. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65794. * @returns The render target texture if present otherwise, null
  65795. */
  65796. ShadowGenerator.prototype.getShadowMap = function () {
  65797. return this._shadowMap;
  65798. };
  65799. /**
  65800. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65801. * @returns The render target texture if the shadow map is present otherwise, null
  65802. */
  65803. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65804. if (this._shadowMap2) {
  65805. return this._shadowMap2;
  65806. }
  65807. return this._shadowMap;
  65808. };
  65809. /**
  65810. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65811. * @param mesh Mesh to add
  65812. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65813. * @returns the Shadow Generator itself
  65814. */
  65815. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65816. if (includeDescendants === void 0) { includeDescendants = true; }
  65817. if (!this._shadowMap) {
  65818. return this;
  65819. }
  65820. if (!this._shadowMap.renderList) {
  65821. this._shadowMap.renderList = [];
  65822. }
  65823. this._shadowMap.renderList.push(mesh);
  65824. if (includeDescendants) {
  65825. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65826. }
  65827. return this;
  65828. var _a;
  65829. };
  65830. /**
  65831. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65832. * @param mesh Mesh to remove
  65833. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65834. * @returns the Shadow Generator itself
  65835. */
  65836. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65837. if (includeDescendants === void 0) { includeDescendants = true; }
  65838. if (!this._shadowMap || !this._shadowMap.renderList) {
  65839. return this;
  65840. }
  65841. var index = this._shadowMap.renderList.indexOf(mesh);
  65842. if (index !== -1) {
  65843. this._shadowMap.renderList.splice(index, 1);
  65844. }
  65845. if (includeDescendants) {
  65846. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65847. var child = _a[_i];
  65848. this.removeShadowCaster(child);
  65849. }
  65850. }
  65851. return this;
  65852. };
  65853. /**
  65854. * Returns the associated light object.
  65855. * @returns the light generating the shadow
  65856. */
  65857. ShadowGenerator.prototype.getLight = function () {
  65858. return this._light;
  65859. };
  65860. ShadowGenerator.prototype._initializeGenerator = function () {
  65861. this._light._markMeshesAsLightDirty();
  65862. this._initializeShadowMap();
  65863. };
  65864. ShadowGenerator.prototype._initializeShadowMap = function () {
  65865. var _this = this;
  65866. // Render target
  65867. var engine = this._scene.getEngine();
  65868. if (engine.webGLVersion > 1) {
  65869. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65870. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65871. }
  65872. else {
  65873. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65874. }
  65875. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65876. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65877. this._shadowMap.anisotropicFilteringLevel = 1;
  65878. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65879. this._shadowMap.renderParticles = false;
  65880. this._shadowMap.ignoreCameraViewport = true;
  65881. // Record Face Index before render.
  65882. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65883. _this._currentFaceIndex = faceIndex;
  65884. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65885. engine.setColorWrite(false);
  65886. }
  65887. });
  65888. // Custom render function.
  65889. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65890. // Blur if required afer render.
  65891. this._shadowMap.onAfterUnbindObservable.add(function () {
  65892. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65893. engine.setColorWrite(true);
  65894. }
  65895. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65896. return;
  65897. }
  65898. var shadowMap = _this.getShadowMapForRendering();
  65899. if (shadowMap) {
  65900. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65901. }
  65902. });
  65903. // Clear according to the chosen filter.
  65904. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65905. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65906. this._shadowMap.onClearObservable.add(function (engine) {
  65907. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65908. engine.clear(clearOne, false, true, false);
  65909. }
  65910. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65911. engine.clear(clearZero, true, true, false);
  65912. }
  65913. else {
  65914. engine.clear(clearOne, true, true, false);
  65915. }
  65916. });
  65917. };
  65918. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65919. var _this = this;
  65920. var engine = this._scene.getEngine();
  65921. var targetSize = this._mapSize / this.blurScale;
  65922. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65923. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65924. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65925. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65926. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65927. }
  65928. if (this.useKernelBlur) {
  65929. 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);
  65930. this._kernelBlurXPostprocess.width = targetSize;
  65931. this._kernelBlurXPostprocess.height = targetSize;
  65932. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65933. effect.setTexture("textureSampler", _this._shadowMap);
  65934. });
  65935. 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);
  65936. this._kernelBlurXPostprocess.autoClear = false;
  65937. this._kernelBlurYPostprocess.autoClear = false;
  65938. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65939. this._kernelBlurXPostprocess.packedFloat = true;
  65940. this._kernelBlurYPostprocess.packedFloat = true;
  65941. }
  65942. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65943. }
  65944. else {
  65945. 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);
  65946. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65947. effect.setFloat2("screenSize", targetSize, targetSize);
  65948. effect.setTexture("textureSampler", _this._shadowMap);
  65949. });
  65950. this._boxBlurPostprocess.autoClear = false;
  65951. this._blurPostProcesses = [this._boxBlurPostprocess];
  65952. }
  65953. };
  65954. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65955. var index;
  65956. var engine = this._scene.getEngine();
  65957. if (depthOnlySubMeshes.length) {
  65958. engine.setColorWrite(false);
  65959. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65960. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65961. }
  65962. engine.setColorWrite(true);
  65963. }
  65964. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65965. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65966. }
  65967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65968. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65969. }
  65970. if (this._transparencyShadow) {
  65971. for (index = 0; index < transparentSubMeshes.length; index++) {
  65972. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65973. }
  65974. }
  65975. };
  65976. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65977. var _this = this;
  65978. var mesh = subMesh.getRenderingMesh();
  65979. var scene = this._scene;
  65980. var engine = scene.getEngine();
  65981. var material = subMesh.getMaterial();
  65982. if (!material) {
  65983. return;
  65984. }
  65985. // Culling
  65986. engine.setState(material.backFaceCulling);
  65987. // Managing instances
  65988. var batch = mesh._getInstancesRenderList(subMesh._id);
  65989. if (batch.mustReturn) {
  65990. return;
  65991. }
  65992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65993. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65994. engine.enableEffect(this._effect);
  65995. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65996. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65997. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65998. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65999. this._effect.setVector3("lightData", this._cachedDirection);
  66000. }
  66001. else {
  66002. this._effect.setVector3("lightData", this._cachedPosition);
  66003. }
  66004. if (scene.activeCamera) {
  66005. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66006. }
  66007. // Alpha test
  66008. if (material && material.needAlphaTesting()) {
  66009. var alphaTexture = material.getAlphaTestTexture();
  66010. if (alphaTexture) {
  66011. this._effect.setTexture("diffuseSampler", alphaTexture);
  66012. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66013. }
  66014. }
  66015. // Bones
  66016. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66017. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66018. }
  66019. // Morph targets
  66020. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66021. if (this.forceBackFacesOnly) {
  66022. engine.setState(true, 0, false, true);
  66023. }
  66024. // Draw
  66025. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66026. if (this.forceBackFacesOnly) {
  66027. engine.setState(true, 0, false, false);
  66028. }
  66029. }
  66030. else {
  66031. // Need to reset refresh rate of the shadowMap
  66032. if (this._shadowMap) {
  66033. this._shadowMap.resetRefreshCounter();
  66034. }
  66035. }
  66036. };
  66037. ShadowGenerator.prototype._applyFilterValues = function () {
  66038. if (!this._shadowMap) {
  66039. return;
  66040. }
  66041. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66042. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66043. }
  66044. else {
  66045. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66046. }
  66047. };
  66048. /**
  66049. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66050. * @param onCompiled Callback triggered at the and of the effects compilation
  66051. * @param options Sets of optional options forcing the compilation with different modes
  66052. */
  66053. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66054. var _this = this;
  66055. var localOptions = __assign({ useInstances: false }, options);
  66056. var shadowMap = this.getShadowMap();
  66057. if (!shadowMap) {
  66058. if (onCompiled) {
  66059. onCompiled(this);
  66060. }
  66061. return;
  66062. }
  66063. var renderList = shadowMap.renderList;
  66064. if (!renderList) {
  66065. if (onCompiled) {
  66066. onCompiled(this);
  66067. }
  66068. return;
  66069. }
  66070. var subMeshes = new Array();
  66071. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66072. var mesh = renderList_1[_i];
  66073. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66074. }
  66075. if (subMeshes.length === 0) {
  66076. if (onCompiled) {
  66077. onCompiled(this);
  66078. }
  66079. return;
  66080. }
  66081. var currentIndex = 0;
  66082. var checkReady = function () {
  66083. if (!_this._scene || !_this._scene.getEngine()) {
  66084. return;
  66085. }
  66086. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66087. currentIndex++;
  66088. if (currentIndex >= subMeshes.length) {
  66089. if (onCompiled) {
  66090. onCompiled(_this);
  66091. }
  66092. return;
  66093. }
  66094. }
  66095. setTimeout(checkReady, 16);
  66096. };
  66097. checkReady();
  66098. };
  66099. /**
  66100. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66101. * @param options Sets of optional options forcing the compilation with different modes
  66102. * @returns A promise that resolves when the compilation completes
  66103. */
  66104. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66105. var _this = this;
  66106. return new Promise(function (resolve) {
  66107. _this.forceCompilation(function () {
  66108. resolve();
  66109. }, options);
  66110. });
  66111. };
  66112. /**
  66113. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66114. * @param subMesh The submesh we want to render in the shadow map
  66115. * @param useInstances Defines wether will draw in the map using instances
  66116. * @returns true if ready otherwise, false
  66117. */
  66118. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66119. var defines = [];
  66120. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66121. defines.push("#define FLOAT");
  66122. }
  66123. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66124. defines.push("#define ESM");
  66125. }
  66126. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66127. defines.push("#define DEPTHTEXTURE");
  66128. }
  66129. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66130. var mesh = subMesh.getMesh();
  66131. var material = subMesh.getMaterial();
  66132. // Normal bias.
  66133. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66134. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66135. defines.push("#define NORMAL");
  66136. if (mesh.nonUniformScaling) {
  66137. defines.push("#define NONUNIFORMSCALING");
  66138. }
  66139. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66140. defines.push("#define DIRECTIONINLIGHTDATA");
  66141. }
  66142. }
  66143. // Alpha test
  66144. if (material && material.needAlphaTesting()) {
  66145. var alphaTexture = material.getAlphaTestTexture();
  66146. if (alphaTexture) {
  66147. defines.push("#define ALPHATEST");
  66148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66149. attribs.push(BABYLON.VertexBuffer.UVKind);
  66150. defines.push("#define UV1");
  66151. }
  66152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66153. if (alphaTexture.coordinatesIndex === 1) {
  66154. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66155. defines.push("#define UV2");
  66156. }
  66157. }
  66158. }
  66159. }
  66160. // Bones
  66161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66164. if (mesh.numBoneInfluencers > 4) {
  66165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66167. }
  66168. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66169. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66170. }
  66171. else {
  66172. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66173. }
  66174. // Morph targets
  66175. var manager = mesh.morphTargetManager;
  66176. var morphInfluencers = 0;
  66177. if (manager) {
  66178. if (manager.numInfluencers > 0) {
  66179. defines.push("#define MORPHTARGETS");
  66180. morphInfluencers = manager.numInfluencers;
  66181. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66182. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66183. }
  66184. }
  66185. // Instances
  66186. if (useInstances) {
  66187. defines.push("#define INSTANCES");
  66188. attribs.push("world0");
  66189. attribs.push("world1");
  66190. attribs.push("world2");
  66191. attribs.push("world3");
  66192. }
  66193. // Get correct effect
  66194. var join = defines.join("\n");
  66195. if (this._cachedDefines !== join) {
  66196. this._cachedDefines = join;
  66197. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66198. }
  66199. if (!this._effect.isReady()) {
  66200. return false;
  66201. }
  66202. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66203. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66204. this._initializeBlurRTTAndPostProcesses();
  66205. }
  66206. }
  66207. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66208. return false;
  66209. }
  66210. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66211. return false;
  66212. }
  66213. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66214. return false;
  66215. }
  66216. return true;
  66217. };
  66218. /**
  66219. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66220. * @param defines Defines of the material we want to update
  66221. * @param lightIndex Index of the light in the enabled light list of the material
  66222. */
  66223. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66224. var scene = this._scene;
  66225. var light = this._light;
  66226. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66227. return;
  66228. }
  66229. defines["SHADOW" + lightIndex] = true;
  66230. if (this.useContactHardeningShadow) {
  66231. defines["SHADOWPCSS" + lightIndex] = true;
  66232. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66233. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66234. }
  66235. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66236. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66237. }
  66238. // else default to high.
  66239. }
  66240. if (this.usePercentageCloserFiltering) {
  66241. defines["SHADOWPCF" + lightIndex] = true;
  66242. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66243. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66244. }
  66245. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66246. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66247. }
  66248. // else default to high.
  66249. }
  66250. else if (this.usePoissonSampling) {
  66251. defines["SHADOWPOISSON" + lightIndex] = true;
  66252. }
  66253. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66254. defines["SHADOWESM" + lightIndex] = true;
  66255. }
  66256. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66257. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66258. }
  66259. if (light.needCube()) {
  66260. defines["SHADOWCUBE" + lightIndex] = true;
  66261. }
  66262. };
  66263. /**
  66264. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66265. * defined in the generator but impacting the effect).
  66266. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66267. * @param effect The effect we are binfing the information for
  66268. */
  66269. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66270. var light = this._light;
  66271. var scene = this._scene;
  66272. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66273. return;
  66274. }
  66275. var camera = scene.activeCamera;
  66276. if (!camera) {
  66277. return;
  66278. }
  66279. var shadowMap = this.getShadowMap();
  66280. if (!shadowMap) {
  66281. return;
  66282. }
  66283. if (!light.needCube()) {
  66284. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66285. }
  66286. // Only PCF uses depth stencil texture.
  66287. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66288. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66289. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66290. }
  66291. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66292. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66293. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66294. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66295. }
  66296. else {
  66297. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66298. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66299. }
  66300. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66301. };
  66302. /**
  66303. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66304. * (eq to shadow prjection matrix * light transform matrix)
  66305. * @returns The transform matrix used to create the shadow map
  66306. */
  66307. ShadowGenerator.prototype.getTransformMatrix = function () {
  66308. var scene = this._scene;
  66309. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66310. return this._transformMatrix;
  66311. }
  66312. this._currentRenderID = scene.getRenderId();
  66313. this._currentFaceIndexCache = this._currentFaceIndex;
  66314. var lightPosition = this._light.position;
  66315. if (this._light.computeTransformedInformation()) {
  66316. lightPosition = this._light.transformedPosition;
  66317. }
  66318. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66319. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66320. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66321. }
  66322. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66323. this._cachedPosition.copyFrom(lightPosition);
  66324. this._cachedDirection.copyFrom(this._lightDirection);
  66325. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66326. var shadowMap = this.getShadowMap();
  66327. if (shadowMap) {
  66328. var renderList = shadowMap.renderList;
  66329. if (renderList) {
  66330. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66331. }
  66332. }
  66333. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66334. }
  66335. return this._transformMatrix;
  66336. };
  66337. /**
  66338. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66339. * Cube and 2D textures for instance.
  66340. */
  66341. ShadowGenerator.prototype.recreateShadowMap = function () {
  66342. var shadowMap = this._shadowMap;
  66343. if (!shadowMap) {
  66344. return;
  66345. }
  66346. // Track render list.
  66347. var renderList = shadowMap.renderList;
  66348. // Clean up existing data.
  66349. this._disposeRTTandPostProcesses();
  66350. // Reinitializes.
  66351. this._initializeGenerator();
  66352. // Reaffect the filter to ensure a correct fallback if necessary.
  66353. this.filter = this.filter;
  66354. // Reaffect the filter.
  66355. this._applyFilterValues();
  66356. // Reaffect Render List.
  66357. this._shadowMap.renderList = renderList;
  66358. };
  66359. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66360. if (this._shadowMap2) {
  66361. this._shadowMap2.dispose();
  66362. this._shadowMap2 = null;
  66363. }
  66364. if (this._boxBlurPostprocess) {
  66365. this._boxBlurPostprocess.dispose();
  66366. this._boxBlurPostprocess = null;
  66367. }
  66368. if (this._kernelBlurXPostprocess) {
  66369. this._kernelBlurXPostprocess.dispose();
  66370. this._kernelBlurXPostprocess = null;
  66371. }
  66372. if (this._kernelBlurYPostprocess) {
  66373. this._kernelBlurYPostprocess.dispose();
  66374. this._kernelBlurYPostprocess = null;
  66375. }
  66376. this._blurPostProcesses = [];
  66377. };
  66378. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66379. if (this._shadowMap) {
  66380. this._shadowMap.dispose();
  66381. this._shadowMap = null;
  66382. }
  66383. this._disposeBlurPostProcesses();
  66384. };
  66385. /**
  66386. * Disposes the ShadowGenerator.
  66387. * Returns nothing.
  66388. */
  66389. ShadowGenerator.prototype.dispose = function () {
  66390. this._disposeRTTandPostProcesses();
  66391. if (this._light) {
  66392. this._light._shadowGenerator = null;
  66393. this._light._markMeshesAsLightDirty();
  66394. }
  66395. };
  66396. /**
  66397. * Serializes the shadow generator setup to a json object.
  66398. * @returns The serialized JSON object
  66399. */
  66400. ShadowGenerator.prototype.serialize = function () {
  66401. var serializationObject = {};
  66402. var shadowMap = this.getShadowMap();
  66403. if (!shadowMap) {
  66404. return serializationObject;
  66405. }
  66406. serializationObject.lightId = this._light.id;
  66407. serializationObject.mapSize = shadowMap.getRenderSize();
  66408. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66409. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66410. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66411. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66412. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66413. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66414. serializationObject.depthScale = this.depthScale;
  66415. serializationObject.darkness = this.getDarkness();
  66416. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66417. serializationObject.blurKernel = this.blurKernel;
  66418. serializationObject.blurScale = this.blurScale;
  66419. serializationObject.useKernelBlur = this.useKernelBlur;
  66420. serializationObject.transparencyShadow = this._transparencyShadow;
  66421. serializationObject.bias = this.bias;
  66422. serializationObject.normalBias = this.normalBias;
  66423. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66424. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66425. serializationObject.filteringQuality = this.filteringQuality;
  66426. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66427. serializationObject.renderList = [];
  66428. if (shadowMap.renderList) {
  66429. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66430. var mesh = shadowMap.renderList[meshIndex];
  66431. serializationObject.renderList.push(mesh.id);
  66432. }
  66433. }
  66434. return serializationObject;
  66435. };
  66436. /**
  66437. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66438. * @param parsedShadowGenerator The JSON object to parse
  66439. * @param scene The scene to create the shadow map for
  66440. * @returns The parsed shadow generator
  66441. */
  66442. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66443. //casting to point light, as light is missing the position attr and typescript complains.
  66444. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66445. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66446. var shadowMap = shadowGenerator.getShadowMap();
  66447. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66448. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66449. meshes.forEach(function (mesh) {
  66450. if (!shadowMap) {
  66451. return;
  66452. }
  66453. if (!shadowMap.renderList) {
  66454. shadowMap.renderList = [];
  66455. }
  66456. shadowMap.renderList.push(mesh);
  66457. });
  66458. }
  66459. if (parsedShadowGenerator.usePoissonSampling) {
  66460. shadowGenerator.usePoissonSampling = true;
  66461. }
  66462. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66463. shadowGenerator.useExponentialShadowMap = true;
  66464. }
  66465. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66466. shadowGenerator.useBlurExponentialShadowMap = true;
  66467. }
  66468. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66469. shadowGenerator.useCloseExponentialShadowMap = true;
  66470. }
  66471. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66472. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66473. }
  66474. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66475. shadowGenerator.usePercentageCloserFiltering = true;
  66476. }
  66477. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66478. shadowGenerator.useContactHardeningShadow = true;
  66479. }
  66480. if (parsedShadowGenerator.filteringQuality) {
  66481. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66482. }
  66483. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66484. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66485. }
  66486. // Backward compat
  66487. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66488. shadowGenerator.useExponentialShadowMap = true;
  66489. }
  66490. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66491. shadowGenerator.useBlurExponentialShadowMap = true;
  66492. }
  66493. if (parsedShadowGenerator.depthScale) {
  66494. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66495. }
  66496. if (parsedShadowGenerator.blurScale) {
  66497. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66498. }
  66499. if (parsedShadowGenerator.blurBoxOffset) {
  66500. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66501. }
  66502. if (parsedShadowGenerator.useKernelBlur) {
  66503. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66504. }
  66505. if (parsedShadowGenerator.blurKernel) {
  66506. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66507. }
  66508. if (parsedShadowGenerator.bias !== undefined) {
  66509. shadowGenerator.bias = parsedShadowGenerator.bias;
  66510. }
  66511. if (parsedShadowGenerator.normalBias !== undefined) {
  66512. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66513. }
  66514. if (parsedShadowGenerator.darkness) {
  66515. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66516. }
  66517. if (parsedShadowGenerator.transparencyShadow) {
  66518. shadowGenerator.setTransparencyShadow(true);
  66519. }
  66520. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66521. return shadowGenerator;
  66522. };
  66523. /**
  66524. * Shadow generator mode None: no filtering applied.
  66525. */
  66526. ShadowGenerator.FILTER_NONE = 0;
  66527. /**
  66528. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66529. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66530. */
  66531. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66532. /**
  66533. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66534. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66535. */
  66536. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66537. /**
  66538. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66539. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66540. */
  66541. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66542. /**
  66543. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66544. * edge artifacts on steep falloff.
  66545. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66546. */
  66547. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66548. /**
  66549. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66550. * edge artifacts on steep falloff.
  66551. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66552. */
  66553. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66554. /**
  66555. * Shadow generator mode PCF: Percentage Closer Filtering
  66556. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66557. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66558. */
  66559. ShadowGenerator.FILTER_PCF = 6;
  66560. /**
  66561. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66562. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66563. * Contact Hardening
  66564. */
  66565. ShadowGenerator.FILTER_PCSS = 7;
  66566. /**
  66567. * Reserved for PCF and PCSS
  66568. * Highest Quality.
  66569. *
  66570. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66571. *
  66572. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66573. */
  66574. ShadowGenerator.QUALITY_HIGH = 0;
  66575. /**
  66576. * Reserved for PCF and PCSS
  66577. * Good tradeoff for quality/perf cross devices
  66578. *
  66579. * Execute PCF on a 3*3 kernel.
  66580. *
  66581. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66582. */
  66583. ShadowGenerator.QUALITY_MEDIUM = 1;
  66584. /**
  66585. * Reserved for PCF and PCSS
  66586. * The lowest quality but the fastest.
  66587. *
  66588. * Execute PCF on a 1*1 kernel.
  66589. *
  66590. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66591. */
  66592. ShadowGenerator.QUALITY_LOW = 2;
  66593. return ShadowGenerator;
  66594. }());
  66595. BABYLON.ShadowGenerator = ShadowGenerator;
  66596. })(BABYLON || (BABYLON = {}));
  66597. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66598. var BABYLON;
  66599. (function (BABYLON) {
  66600. var DefaultLoadingScreen = /** @class */ (function () {
  66601. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66602. if (_loadingText === void 0) { _loadingText = ""; }
  66603. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66604. var _this = this;
  66605. this._renderingCanvas = _renderingCanvas;
  66606. this._loadingText = _loadingText;
  66607. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66608. // Resize
  66609. this._resizeLoadingUI = function () {
  66610. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66611. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66612. if (!_this._loadingDiv) {
  66613. return;
  66614. }
  66615. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66616. _this._loadingDiv.style.left = canvasRect.left + "px";
  66617. _this._loadingDiv.style.top = canvasRect.top + "px";
  66618. _this._loadingDiv.style.width = canvasRect.width + "px";
  66619. _this._loadingDiv.style.height = canvasRect.height + "px";
  66620. };
  66621. }
  66622. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66623. if (this._loadingDiv) {
  66624. // Do not add a loading screen if there is already one
  66625. return;
  66626. }
  66627. this._loadingDiv = document.createElement("div");
  66628. this._loadingDiv.id = "babylonjsLoadingDiv";
  66629. this._loadingDiv.style.opacity = "0";
  66630. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66631. this._loadingDiv.style.pointerEvents = "none";
  66632. // Loading text
  66633. this._loadingTextDiv = document.createElement("div");
  66634. this._loadingTextDiv.style.position = "absolute";
  66635. this._loadingTextDiv.style.left = "0";
  66636. this._loadingTextDiv.style.top = "50%";
  66637. this._loadingTextDiv.style.marginTop = "80px";
  66638. this._loadingTextDiv.style.width = "100%";
  66639. this._loadingTextDiv.style.height = "20px";
  66640. this._loadingTextDiv.style.fontFamily = "Arial";
  66641. this._loadingTextDiv.style.fontSize = "14px";
  66642. this._loadingTextDiv.style.color = "white";
  66643. this._loadingTextDiv.style.textAlign = "center";
  66644. this._loadingTextDiv.innerHTML = "Loading";
  66645. this._loadingDiv.appendChild(this._loadingTextDiv);
  66646. //set the predefined text
  66647. this._loadingTextDiv.innerHTML = this._loadingText;
  66648. // Generating keyframes
  66649. var style = document.createElement('style');
  66650. style.type = 'text/css';
  66651. 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 }";
  66652. style.innerHTML = keyFrames;
  66653. document.getElementsByTagName('head')[0].appendChild(style);
  66654. // Loading img
  66655. var imgBack = new Image();
  66656. 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";
  66657. imgBack.style.position = "absolute";
  66658. imgBack.style.left = "50%";
  66659. imgBack.style.top = "50%";
  66660. imgBack.style.marginLeft = "-60px";
  66661. imgBack.style.marginTop = "-60px";
  66662. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66663. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66664. imgBack.style.transformOrigin = "50% 50%";
  66665. imgBack.style.webkitTransformOrigin = "50% 50%";
  66666. this._loadingDiv.appendChild(imgBack);
  66667. this._resizeLoadingUI();
  66668. window.addEventListener("resize", this._resizeLoadingUI);
  66669. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66670. document.body.appendChild(this._loadingDiv);
  66671. this._loadingDiv.style.opacity = "1";
  66672. };
  66673. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66674. var _this = this;
  66675. if (!this._loadingDiv) {
  66676. return;
  66677. }
  66678. var onTransitionEnd = function () {
  66679. if (!_this._loadingDiv) {
  66680. return;
  66681. }
  66682. document.body.removeChild(_this._loadingDiv);
  66683. window.removeEventListener("resize", _this._resizeLoadingUI);
  66684. _this._loadingDiv = null;
  66685. };
  66686. this._loadingDiv.style.opacity = "0";
  66687. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66688. };
  66689. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66690. set: function (text) {
  66691. this._loadingText = text;
  66692. if (this._loadingTextDiv) {
  66693. this._loadingTextDiv.innerHTML = this._loadingText;
  66694. }
  66695. },
  66696. enumerable: true,
  66697. configurable: true
  66698. });
  66699. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66700. get: function () {
  66701. return this._loadingDivBackgroundColor;
  66702. },
  66703. set: function (color) {
  66704. this._loadingDivBackgroundColor = color;
  66705. if (!this._loadingDiv) {
  66706. return;
  66707. }
  66708. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66709. },
  66710. enumerable: true,
  66711. configurable: true
  66712. });
  66713. return DefaultLoadingScreen;
  66714. }());
  66715. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66716. })(BABYLON || (BABYLON = {}));
  66717. //# sourceMappingURL=babylon.loadingScreen.js.map
  66718. var BABYLON;
  66719. (function (BABYLON) {
  66720. var SceneLoaderProgressEvent = /** @class */ (function () {
  66721. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66722. this.lengthComputable = lengthComputable;
  66723. this.loaded = loaded;
  66724. this.total = total;
  66725. }
  66726. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66727. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66728. };
  66729. return SceneLoaderProgressEvent;
  66730. }());
  66731. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66732. var SceneLoader = /** @class */ (function () {
  66733. function SceneLoader() {
  66734. }
  66735. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66736. get: function () {
  66737. return 0;
  66738. },
  66739. enumerable: true,
  66740. configurable: true
  66741. });
  66742. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66743. get: function () {
  66744. return 1;
  66745. },
  66746. enumerable: true,
  66747. configurable: true
  66748. });
  66749. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66750. get: function () {
  66751. return 2;
  66752. },
  66753. enumerable: true,
  66754. configurable: true
  66755. });
  66756. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66757. get: function () {
  66758. return 3;
  66759. },
  66760. enumerable: true,
  66761. configurable: true
  66762. });
  66763. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66764. get: function () {
  66765. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66766. },
  66767. set: function (value) {
  66768. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66769. },
  66770. enumerable: true,
  66771. configurable: true
  66772. });
  66773. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66774. get: function () {
  66775. return SceneLoader._ShowLoadingScreen;
  66776. },
  66777. set: function (value) {
  66778. SceneLoader._ShowLoadingScreen = value;
  66779. },
  66780. enumerable: true,
  66781. configurable: true
  66782. });
  66783. Object.defineProperty(SceneLoader, "loggingLevel", {
  66784. get: function () {
  66785. return SceneLoader._loggingLevel;
  66786. },
  66787. set: function (value) {
  66788. SceneLoader._loggingLevel = value;
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66794. get: function () {
  66795. return SceneLoader._CleanBoneMatrixWeights;
  66796. },
  66797. set: function (value) {
  66798. SceneLoader._CleanBoneMatrixWeights = value;
  66799. },
  66800. enumerable: true,
  66801. configurable: true
  66802. });
  66803. SceneLoader._getDefaultPlugin = function () {
  66804. return SceneLoader._registeredPlugins[".babylon"];
  66805. };
  66806. SceneLoader._getPluginForExtension = function (extension) {
  66807. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66808. if (registeredPlugin) {
  66809. return registeredPlugin;
  66810. }
  66811. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66812. return SceneLoader._getDefaultPlugin();
  66813. };
  66814. SceneLoader._getPluginForDirectLoad = function (data) {
  66815. for (var extension in SceneLoader._registeredPlugins) {
  66816. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66817. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66818. return SceneLoader._registeredPlugins[extension];
  66819. }
  66820. }
  66821. return SceneLoader._getDefaultPlugin();
  66822. };
  66823. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66824. if (sceneFilename.name) {
  66825. sceneFilename = sceneFilename.name;
  66826. }
  66827. var queryStringPosition = sceneFilename.indexOf("?");
  66828. if (queryStringPosition !== -1) {
  66829. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66830. }
  66831. var dotPosition = sceneFilename.lastIndexOf(".");
  66832. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66833. return SceneLoader._getPluginForExtension(extension);
  66834. };
  66835. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66836. SceneLoader._getDirectLoad = function (sceneFilename) {
  66837. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66838. return sceneFilename.substr(5);
  66839. }
  66840. return null;
  66841. };
  66842. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66843. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66844. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66845. var plugin;
  66846. if (registeredPlugin.plugin.createPlugin) {
  66847. plugin = registeredPlugin.plugin.createPlugin();
  66848. }
  66849. else {
  66850. plugin = registeredPlugin.plugin;
  66851. }
  66852. var useArrayBuffer = registeredPlugin.isBinary;
  66853. var database;
  66854. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66855. var dataCallback = function (data, responseURL) {
  66856. if (scene.isDisposed) {
  66857. onError("Scene has been disposed");
  66858. return;
  66859. }
  66860. scene.database = database;
  66861. onSuccess(plugin, data, responseURL);
  66862. };
  66863. var request = null;
  66864. var pluginDisposed = false;
  66865. var onDisposeObservable = plugin.onDisposeObservable;
  66866. if (onDisposeObservable) {
  66867. onDisposeObservable.add(function () {
  66868. pluginDisposed = true;
  66869. if (request) {
  66870. request.abort();
  66871. request = null;
  66872. }
  66873. onDispose();
  66874. });
  66875. }
  66876. var manifestChecked = function () {
  66877. if (pluginDisposed) {
  66878. return;
  66879. }
  66880. var url = rootUrl + sceneFilename;
  66881. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66882. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66883. } : undefined, database, useArrayBuffer, function (request, exception) {
  66884. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66885. });
  66886. };
  66887. if (directLoad) {
  66888. dataCallback(directLoad);
  66889. return plugin;
  66890. }
  66891. if (rootUrl.indexOf("file:") === -1) {
  66892. var engine = scene.getEngine();
  66893. var canUseOfflineSupport = engine.enableOfflineSupport;
  66894. if (canUseOfflineSupport) {
  66895. // Also check for exceptions
  66896. var exceptionFound = false;
  66897. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66898. var regex = _a[_i];
  66899. if (regex.test(rootUrl + sceneFilename)) {
  66900. exceptionFound = true;
  66901. break;
  66902. }
  66903. }
  66904. canUseOfflineSupport = !exceptionFound;
  66905. }
  66906. if (canUseOfflineSupport) {
  66907. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66908. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66909. }
  66910. else {
  66911. manifestChecked();
  66912. }
  66913. }
  66914. // Loading file from disk via input file or drag'n'drop
  66915. else {
  66916. var fileOrString = sceneFilename;
  66917. if (fileOrString.name) { // File
  66918. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66919. }
  66920. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66921. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66922. }
  66923. else {
  66924. onError("Unable to find file named " + sceneFilename);
  66925. }
  66926. }
  66927. return plugin;
  66928. };
  66929. // Public functions
  66930. SceneLoader.GetPluginForExtension = function (extension) {
  66931. return SceneLoader._getPluginForExtension(extension).plugin;
  66932. };
  66933. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66934. return !!SceneLoader._registeredPlugins[extension];
  66935. };
  66936. SceneLoader.RegisterPlugin = function (plugin) {
  66937. if (typeof plugin.extensions === "string") {
  66938. var extension = plugin.extensions;
  66939. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66940. plugin: plugin,
  66941. isBinary: false
  66942. };
  66943. }
  66944. else {
  66945. var extensions = plugin.extensions;
  66946. Object.keys(extensions).forEach(function (extension) {
  66947. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66948. plugin: plugin,
  66949. isBinary: extensions[extension].isBinary
  66950. };
  66951. });
  66952. }
  66953. };
  66954. /**
  66955. * Import meshes into a scene
  66956. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66957. * @param rootUrl a string that defines the root url for scene and resources
  66958. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66959. * @param scene the instance of BABYLON.Scene to append to
  66960. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66961. * @param onProgress a callback with a progress event for each file being loaded
  66962. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66963. * @param pluginExtension the extension used to determine the plugin
  66964. * @returns The loaded plugin
  66965. */
  66966. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66967. if (onSuccess === void 0) { onSuccess = null; }
  66968. if (onProgress === void 0) { onProgress = null; }
  66969. if (onError === void 0) { onError = null; }
  66970. if (pluginExtension === void 0) { pluginExtension = null; }
  66971. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66972. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66973. return null;
  66974. }
  66975. var loadingToken = {};
  66976. scene._addPendingData(loadingToken);
  66977. var disposeHandler = function () {
  66978. scene._removePendingData(loadingToken);
  66979. };
  66980. var errorHandler = function (message, exception) {
  66981. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66982. if (onError) {
  66983. onError(scene, errorMessage, exception);
  66984. }
  66985. else {
  66986. BABYLON.Tools.Error(errorMessage);
  66987. // should the exception be thrown?
  66988. }
  66989. disposeHandler();
  66990. };
  66991. var progressHandler = onProgress ? function (event) {
  66992. try {
  66993. onProgress(event);
  66994. }
  66995. catch (e) {
  66996. errorHandler("Error in onProgress callback", e);
  66997. }
  66998. } : undefined;
  66999. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67000. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67001. if (onSuccess) {
  67002. try {
  67003. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67004. }
  67005. catch (e) {
  67006. errorHandler("Error in onSuccess callback", e);
  67007. }
  67008. }
  67009. scene._removePendingData(loadingToken);
  67010. };
  67011. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67012. if (plugin.rewriteRootURL) {
  67013. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67014. }
  67015. if (sceneFilename === "") {
  67016. if (sceneFilename === "") {
  67017. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67018. }
  67019. }
  67020. if (plugin.importMesh) {
  67021. var syncedPlugin = plugin;
  67022. var meshes = new Array();
  67023. var particleSystems = new Array();
  67024. var skeletons = new Array();
  67025. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67026. return;
  67027. }
  67028. scene.loadingPluginName = plugin.name;
  67029. successHandler(meshes, particleSystems, skeletons, []);
  67030. }
  67031. else {
  67032. var asyncedPlugin = plugin;
  67033. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67034. scene.loadingPluginName = plugin.name;
  67035. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67036. }).catch(function (error) {
  67037. errorHandler(error.message, error);
  67038. });
  67039. }
  67040. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67041. };
  67042. /**
  67043. * Import meshes into a scene
  67044. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67045. * @param rootUrl a string that defines the root url for scene and resources
  67046. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67047. * @param scene the instance of BABYLON.Scene to append to
  67048. * @param onProgress a callback with a progress event for each file being loaded
  67049. * @param pluginExtension the extension used to determine the plugin
  67050. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67051. */
  67052. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67053. if (onProgress === void 0) { onProgress = null; }
  67054. if (pluginExtension === void 0) { pluginExtension = null; }
  67055. return new Promise(function (resolve, reject) {
  67056. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67057. resolve({
  67058. meshes: meshes,
  67059. particleSystems: particleSystems,
  67060. skeletons: skeletons,
  67061. animationGroups: animationGroups
  67062. });
  67063. }, onProgress, function (scene, message, exception) {
  67064. reject(exception || new Error(message));
  67065. }, pluginExtension);
  67066. });
  67067. };
  67068. /**
  67069. * Load a scene
  67070. * @param rootUrl a string that defines the root url for scene and resources
  67071. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67072. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67073. * @param onSuccess a callback with the scene when import succeeds
  67074. * @param onProgress a callback with a progress event for each file being loaded
  67075. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67076. * @param pluginExtension the extension used to determine the plugin
  67077. * @returns The loaded plugin
  67078. */
  67079. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67080. if (onSuccess === void 0) { onSuccess = null; }
  67081. if (onProgress === void 0) { onProgress = null; }
  67082. if (onError === void 0) { onError = null; }
  67083. if (pluginExtension === void 0) { pluginExtension = null; }
  67084. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67085. };
  67086. /**
  67087. * Load a scene
  67088. * @param rootUrl a string that defines the root url for scene and resources
  67089. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67090. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67091. * @param onProgress a callback with a progress event for each file being loaded
  67092. * @param pluginExtension the extension used to determine the plugin
  67093. * @returns The loaded scene
  67094. */
  67095. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67096. if (onProgress === void 0) { onProgress = null; }
  67097. if (pluginExtension === void 0) { pluginExtension = null; }
  67098. return new Promise(function (resolve, reject) {
  67099. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67100. resolve(scene);
  67101. }, onProgress, function (scene, message, exception) {
  67102. reject(exception || new Error(message));
  67103. }, pluginExtension);
  67104. });
  67105. };
  67106. /**
  67107. * Append a scene
  67108. * @param rootUrl a string that defines the root url for scene and resources
  67109. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67110. * @param scene is the instance of BABYLON.Scene to append to
  67111. * @param onSuccess a callback with the scene when import succeeds
  67112. * @param onProgress a callback with a progress event for each file being loaded
  67113. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67114. * @param pluginExtension the extension used to determine the plugin
  67115. * @returns The loaded plugin
  67116. */
  67117. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67118. if (onSuccess === void 0) { onSuccess = null; }
  67119. if (onProgress === void 0) { onProgress = null; }
  67120. if (onError === void 0) { onError = null; }
  67121. if (pluginExtension === void 0) { pluginExtension = null; }
  67122. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67123. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67124. return null;
  67125. }
  67126. if (SceneLoader.ShowLoadingScreen) {
  67127. scene.getEngine().displayLoadingUI();
  67128. }
  67129. var loadingToken = {};
  67130. scene._addPendingData(loadingToken);
  67131. var disposeHandler = function () {
  67132. scene._removePendingData(loadingToken);
  67133. scene.getEngine().hideLoadingUI();
  67134. };
  67135. var errorHandler = function (message, exception) {
  67136. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67137. if (onError) {
  67138. onError(scene, errorMessage, exception);
  67139. }
  67140. else {
  67141. BABYLON.Tools.Error(errorMessage);
  67142. // should the exception be thrown?
  67143. }
  67144. disposeHandler();
  67145. };
  67146. var progressHandler = onProgress ? function (event) {
  67147. try {
  67148. onProgress(event);
  67149. }
  67150. catch (e) {
  67151. errorHandler("Error in onProgress callback", e);
  67152. }
  67153. } : undefined;
  67154. var successHandler = function () {
  67155. if (onSuccess) {
  67156. try {
  67157. onSuccess(scene);
  67158. }
  67159. catch (e) {
  67160. errorHandler("Error in onSuccess callback", e);
  67161. }
  67162. }
  67163. scene._removePendingData(loadingToken);
  67164. };
  67165. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67166. if (sceneFilename === "") {
  67167. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67168. }
  67169. if (plugin.load) {
  67170. var syncedPlugin = plugin;
  67171. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67172. return;
  67173. }
  67174. scene.loadingPluginName = plugin.name;
  67175. successHandler();
  67176. }
  67177. else {
  67178. var asyncedPlugin = plugin;
  67179. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67180. scene.loadingPluginName = plugin.name;
  67181. successHandler();
  67182. }).catch(function (error) {
  67183. errorHandler(error.message, error);
  67184. });
  67185. }
  67186. if (SceneLoader.ShowLoadingScreen) {
  67187. scene.executeWhenReady(function () {
  67188. scene.getEngine().hideLoadingUI();
  67189. });
  67190. }
  67191. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67192. };
  67193. /**
  67194. * Append a scene
  67195. * @param rootUrl a string that defines the root url for scene and resources
  67196. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67197. * @param scene is the instance of BABYLON.Scene to append to
  67198. * @param onProgress a callback with a progress event for each file being loaded
  67199. * @param pluginExtension the extension used to determine the plugin
  67200. * @returns The given scene
  67201. */
  67202. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67203. if (onProgress === void 0) { onProgress = null; }
  67204. if (pluginExtension === void 0) { pluginExtension = null; }
  67205. return new Promise(function (resolve, reject) {
  67206. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67207. resolve(scene);
  67208. }, onProgress, function (scene, message, exception) {
  67209. reject(exception || new Error(message));
  67210. }, pluginExtension);
  67211. });
  67212. };
  67213. /**
  67214. * Load a scene into an asset container
  67215. * @param rootUrl a string that defines the root url for scene and resources
  67216. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67217. * @param scene is the instance of BABYLON.Scene to append to
  67218. * @param onSuccess a callback with the scene when import succeeds
  67219. * @param onProgress a callback with a progress event for each file being loaded
  67220. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67221. * @param pluginExtension the extension used to determine the plugin
  67222. * @returns The loaded plugin
  67223. */
  67224. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67225. if (onSuccess === void 0) { onSuccess = null; }
  67226. if (onProgress === void 0) { onProgress = null; }
  67227. if (onError === void 0) { onError = null; }
  67228. if (pluginExtension === void 0) { pluginExtension = null; }
  67229. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67230. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67231. return null;
  67232. }
  67233. var loadingToken = {};
  67234. scene._addPendingData(loadingToken);
  67235. var disposeHandler = function () {
  67236. scene._removePendingData(loadingToken);
  67237. };
  67238. var errorHandler = function (message, exception) {
  67239. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67240. if (onError) {
  67241. onError(scene, errorMessage, exception);
  67242. }
  67243. else {
  67244. BABYLON.Tools.Error(errorMessage);
  67245. // should the exception be thrown?
  67246. }
  67247. disposeHandler();
  67248. };
  67249. var progressHandler = onProgress ? function (event) {
  67250. try {
  67251. onProgress(event);
  67252. }
  67253. catch (e) {
  67254. errorHandler("Error in onProgress callback", e);
  67255. }
  67256. } : undefined;
  67257. var successHandler = function (assets) {
  67258. if (onSuccess) {
  67259. try {
  67260. onSuccess(assets);
  67261. }
  67262. catch (e) {
  67263. errorHandler("Error in onSuccess callback", e);
  67264. }
  67265. }
  67266. scene._removePendingData(loadingToken);
  67267. };
  67268. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67269. if (plugin.loadAssetContainer) {
  67270. var syncedPlugin = plugin;
  67271. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67272. if (!assetContainer) {
  67273. return;
  67274. }
  67275. scene.loadingPluginName = plugin.name;
  67276. successHandler(assetContainer);
  67277. }
  67278. else if (plugin.loadAssetContainerAsync) {
  67279. var asyncedPlugin = plugin;
  67280. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67281. scene.loadingPluginName = plugin.name;
  67282. successHandler(assetContainer);
  67283. }).catch(function (error) {
  67284. errorHandler(error.message, error);
  67285. });
  67286. }
  67287. else {
  67288. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67289. }
  67290. if (SceneLoader.ShowLoadingScreen) {
  67291. scene.executeWhenReady(function () {
  67292. scene.getEngine().hideLoadingUI();
  67293. });
  67294. }
  67295. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67296. };
  67297. /**
  67298. * Load a scene into an asset container
  67299. * @param rootUrl a string that defines the root url for scene and resources
  67300. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67301. * @param scene is the instance of BABYLON.Scene to append to
  67302. * @param onProgress a callback with a progress event for each file being loaded
  67303. * @param pluginExtension the extension used to determine the plugin
  67304. * @returns The loaded asset container
  67305. */
  67306. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67307. if (onProgress === void 0) { onProgress = null; }
  67308. if (pluginExtension === void 0) { pluginExtension = null; }
  67309. return new Promise(function (resolve, reject) {
  67310. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67311. resolve(assetContainer);
  67312. }, onProgress, function (scene, message, exception) {
  67313. reject(exception || new Error(message));
  67314. }, pluginExtension);
  67315. });
  67316. };
  67317. // Flags
  67318. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67319. SceneLoader._ShowLoadingScreen = true;
  67320. SceneLoader._CleanBoneMatrixWeights = false;
  67321. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67322. // Members
  67323. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67324. SceneLoader._registeredPlugins = {};
  67325. return SceneLoader;
  67326. }());
  67327. BABYLON.SceneLoader = SceneLoader;
  67328. ;
  67329. })(BABYLON || (BABYLON = {}));
  67330. //# sourceMappingURL=babylon.sceneLoader.js.map
  67331. var BABYLON;
  67332. (function (BABYLON) {
  67333. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67334. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67335. var parsedMaterial = parsedData.materials[index];
  67336. if (parsedMaterial.id === id) {
  67337. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67338. }
  67339. }
  67340. return null;
  67341. };
  67342. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67343. for (var i in names) {
  67344. if (mesh.name === names[i]) {
  67345. hierarchyIds.push(mesh.id);
  67346. return true;
  67347. }
  67348. }
  67349. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67350. hierarchyIds.push(mesh.id);
  67351. return true;
  67352. }
  67353. return false;
  67354. };
  67355. var logOperation = function (operation, producer) {
  67356. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67357. };
  67358. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67359. if (addToScene === void 0) { addToScene = false; }
  67360. var container = new BABYLON.AssetContainer(scene);
  67361. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67362. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67363. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67364. // and avoid problems with multiple concurrent .babylon loads.
  67365. var log = "importScene has failed JSON parse";
  67366. try {
  67367. var parsedData = JSON.parse(data);
  67368. log = "";
  67369. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67370. var index;
  67371. var cache;
  67372. // Lights
  67373. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67374. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67375. var parsedLight = parsedData.lights[index];
  67376. var light = BABYLON.Light.Parse(parsedLight, scene);
  67377. if (light) {
  67378. container.lights.push(light);
  67379. log += (index === 0 ? "\n\tLights:" : "");
  67380. log += "\n\t\t" + light.toString(fullDetails);
  67381. }
  67382. }
  67383. }
  67384. // Animations
  67385. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67386. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67387. var parsedAnimation = parsedData.animations[index];
  67388. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67389. scene.animations.push(animation);
  67390. container.animations.push(animation);
  67391. log += (index === 0 ? "\n\tAnimations:" : "");
  67392. log += "\n\t\t" + animation.toString(fullDetails);
  67393. }
  67394. }
  67395. // Materials
  67396. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67397. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67398. var parsedMaterial = parsedData.materials[index];
  67399. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67400. container.materials.push(mat);
  67401. log += (index === 0 ? "\n\tMaterials:" : "");
  67402. log += "\n\t\t" + mat.toString(fullDetails);
  67403. }
  67404. }
  67405. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67406. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67407. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67408. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67409. container.multiMaterials.push(mmat);
  67410. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67411. log += "\n\t\t" + mmat.toString(fullDetails);
  67412. }
  67413. }
  67414. // Morph targets
  67415. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67416. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67417. var managerData = _a[_i];
  67418. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67419. }
  67420. }
  67421. // Skeletons
  67422. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67423. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67424. var parsedSkeleton = parsedData.skeletons[index];
  67425. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67426. container.skeletons.push(skeleton);
  67427. log += (index === 0 ? "\n\tSkeletons:" : "");
  67428. log += "\n\t\t" + skeleton.toString(fullDetails);
  67429. }
  67430. }
  67431. // Geometries
  67432. var geometries = parsedData.geometries;
  67433. if (geometries !== undefined && geometries !== null) {
  67434. var addedGeometry = new Array();
  67435. // Boxes
  67436. var boxes = geometries.boxes;
  67437. if (boxes !== undefined && boxes !== null) {
  67438. for (index = 0, cache = boxes.length; index < cache; index++) {
  67439. var parsedBox = boxes[index];
  67440. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67441. }
  67442. }
  67443. // Spheres
  67444. var spheres = geometries.spheres;
  67445. if (spheres !== undefined && spheres !== null) {
  67446. for (index = 0, cache = spheres.length; index < cache; index++) {
  67447. var parsedSphere = spheres[index];
  67448. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67449. }
  67450. }
  67451. // Cylinders
  67452. var cylinders = geometries.cylinders;
  67453. if (cylinders !== undefined && cylinders !== null) {
  67454. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67455. var parsedCylinder = cylinders[index];
  67456. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67457. }
  67458. }
  67459. // Toruses
  67460. var toruses = geometries.toruses;
  67461. if (toruses !== undefined && toruses !== null) {
  67462. for (index = 0, cache = toruses.length; index < cache; index++) {
  67463. var parsedTorus = toruses[index];
  67464. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67465. }
  67466. }
  67467. // Grounds
  67468. var grounds = geometries.grounds;
  67469. if (grounds !== undefined && grounds !== null) {
  67470. for (index = 0, cache = grounds.length; index < cache; index++) {
  67471. var parsedGround = grounds[index];
  67472. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67473. }
  67474. }
  67475. // Planes
  67476. var planes = geometries.planes;
  67477. if (planes !== undefined && planes !== null) {
  67478. for (index = 0, cache = planes.length; index < cache; index++) {
  67479. var parsedPlane = planes[index];
  67480. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67481. }
  67482. }
  67483. // TorusKnots
  67484. var torusKnots = geometries.torusKnots;
  67485. if (torusKnots !== undefined && torusKnots !== null) {
  67486. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67487. var parsedTorusKnot = torusKnots[index];
  67488. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67489. }
  67490. }
  67491. // VertexData
  67492. var vertexData = geometries.vertexData;
  67493. if (vertexData !== undefined && vertexData !== null) {
  67494. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67495. var parsedVertexData = vertexData[index];
  67496. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67497. }
  67498. }
  67499. addedGeometry.forEach(function (g) {
  67500. if (g) {
  67501. container.geometries.push(g);
  67502. }
  67503. });
  67504. }
  67505. // Transform nodes
  67506. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67507. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67508. var parsedTransformNode = parsedData.transformNodes[index];
  67509. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67510. container.transformNodes.push(node);
  67511. }
  67512. }
  67513. // Meshes
  67514. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67515. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67516. var parsedMesh = parsedData.meshes[index];
  67517. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67518. container.meshes.push(mesh);
  67519. log += (index === 0 ? "\n\tMeshes:" : "");
  67520. log += "\n\t\t" + mesh.toString(fullDetails);
  67521. }
  67522. }
  67523. // Cameras
  67524. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67525. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67526. var parsedCamera = parsedData.cameras[index];
  67527. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67528. container.cameras.push(camera);
  67529. log += (index === 0 ? "\n\tCameras:" : "");
  67530. log += "\n\t\t" + camera.toString(fullDetails);
  67531. }
  67532. }
  67533. // Browsing all the graph to connect the dots
  67534. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67535. var camera = scene.cameras[index];
  67536. if (camera._waitingParentId) {
  67537. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67538. camera._waitingParentId = null;
  67539. }
  67540. }
  67541. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67542. var light_1 = scene.lights[index];
  67543. if (light_1 && light_1._waitingParentId) {
  67544. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67545. light_1._waitingParentId = null;
  67546. }
  67547. }
  67548. // Sounds
  67549. // TODO: add sound
  67550. var loadedSounds = [];
  67551. var loadedSound;
  67552. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67553. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67554. var parsedSound = parsedData.sounds[index];
  67555. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67556. if (!parsedSound.url)
  67557. parsedSound.url = parsedSound.name;
  67558. if (!loadedSounds[parsedSound.url]) {
  67559. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67560. loadedSounds[parsedSound.url] = loadedSound;
  67561. container.sounds.push(loadedSound);
  67562. }
  67563. else {
  67564. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67565. }
  67566. }
  67567. else {
  67568. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67569. }
  67570. }
  67571. }
  67572. loadedSounds = [];
  67573. // Connect parents & children and parse actions
  67574. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67575. var transformNode = scene.transformNodes[index];
  67576. if (transformNode._waitingParentId) {
  67577. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67578. transformNode._waitingParentId = null;
  67579. }
  67580. }
  67581. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67582. var mesh = scene.meshes[index];
  67583. if (mesh._waitingParentId) {
  67584. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67585. mesh._waitingParentId = null;
  67586. }
  67587. if (mesh._waitingActions) {
  67588. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67589. mesh._waitingActions = null;
  67590. }
  67591. }
  67592. // freeze world matrix application
  67593. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67594. var currentMesh = scene.meshes[index];
  67595. if (currentMesh._waitingFreezeWorldMatrix) {
  67596. currentMesh.freezeWorldMatrix();
  67597. currentMesh._waitingFreezeWorldMatrix = null;
  67598. }
  67599. else {
  67600. currentMesh.computeWorldMatrix(true);
  67601. }
  67602. }
  67603. // Particles Systems
  67604. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67605. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67606. var parsedParticleSystem = parsedData.particleSystems[index];
  67607. if (parsedParticleSystem.activeParticleCount) {
  67608. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67609. container.particleSystems.push(ps);
  67610. }
  67611. else {
  67612. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67613. container.particleSystems.push(ps);
  67614. }
  67615. }
  67616. }
  67617. // Lens flares
  67618. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67619. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67620. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67621. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67622. container.lensFlareSystems.push(lf);
  67623. }
  67624. }
  67625. // Shadows
  67626. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67627. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67628. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67629. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67630. container.shadowGenerators.push(sg);
  67631. }
  67632. }
  67633. // Lights exclusions / inclusions
  67634. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67635. var light_2 = scene.lights[index];
  67636. // Excluded check
  67637. if (light_2._excludedMeshesIds.length > 0) {
  67638. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67639. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67640. if (excludedMesh) {
  67641. light_2.excludedMeshes.push(excludedMesh);
  67642. }
  67643. }
  67644. light_2._excludedMeshesIds = [];
  67645. }
  67646. // Included check
  67647. if (light_2._includedOnlyMeshesIds.length > 0) {
  67648. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67649. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67650. if (includedOnlyMesh) {
  67651. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67652. }
  67653. }
  67654. light_2._includedOnlyMeshesIds = [];
  67655. }
  67656. }
  67657. // Effect layers
  67658. if (parsedData.effectLayers) {
  67659. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67660. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67661. container.effectLayers.push(effectLayer);
  67662. }
  67663. }
  67664. // Actions (scene)
  67665. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67666. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67667. }
  67668. if (!addToScene) {
  67669. container.removeAllFromScene();
  67670. }
  67671. }
  67672. catch (err) {
  67673. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67674. if (onError) {
  67675. onError(msg, err);
  67676. }
  67677. else {
  67678. BABYLON.Tools.Log(msg);
  67679. throw err;
  67680. }
  67681. }
  67682. finally {
  67683. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67684. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67685. }
  67686. }
  67687. return container;
  67688. };
  67689. BABYLON.SceneLoader.RegisterPlugin({
  67690. name: "babylon.js",
  67691. extensions: ".babylon",
  67692. canDirectLoad: function (data) {
  67693. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67694. return true;
  67695. }
  67696. return false;
  67697. },
  67698. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67699. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67700. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67701. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67702. // and avoid problems with multiple concurrent .babylon loads.
  67703. var log = "importMesh has failed JSON parse";
  67704. try {
  67705. var parsedData = JSON.parse(data);
  67706. log = "";
  67707. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67708. if (!meshesNames) {
  67709. meshesNames = null;
  67710. }
  67711. else if (!Array.isArray(meshesNames)) {
  67712. meshesNames = [meshesNames];
  67713. }
  67714. var hierarchyIds = new Array();
  67715. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67716. var loadedSkeletonsIds = [];
  67717. var loadedMaterialsIds = [];
  67718. var index;
  67719. var cache;
  67720. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67721. var parsedMesh = parsedData.meshes[index];
  67722. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67723. if (meshesNames !== null) {
  67724. // Remove found mesh name from list.
  67725. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67726. }
  67727. //Geometry?
  67728. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67729. //does the file contain geometries?
  67730. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67731. //find the correct geometry and add it to the scene
  67732. var found = false;
  67733. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67734. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67735. return;
  67736. }
  67737. else {
  67738. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67739. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67740. switch (geometryType) {
  67741. case "boxes":
  67742. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67743. break;
  67744. case "spheres":
  67745. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67746. break;
  67747. case "cylinders":
  67748. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67749. break;
  67750. case "toruses":
  67751. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67752. break;
  67753. case "grounds":
  67754. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67755. break;
  67756. case "planes":
  67757. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67758. break;
  67759. case "torusKnots":
  67760. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67761. break;
  67762. case "vertexData":
  67763. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67764. break;
  67765. }
  67766. found = true;
  67767. }
  67768. });
  67769. }
  67770. });
  67771. if (found === false) {
  67772. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67773. }
  67774. }
  67775. }
  67776. // Material ?
  67777. if (parsedMesh.materialId) {
  67778. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67779. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67780. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67781. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67782. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67783. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67784. var subMatId = parsedMultiMaterial.materials[matIndex];
  67785. loadedMaterialsIds.push(subMatId);
  67786. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67787. if (mat) {
  67788. log += "\n\tMaterial " + mat.toString(fullDetails);
  67789. }
  67790. }
  67791. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67792. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67793. if (mmat) {
  67794. materialFound = true;
  67795. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67796. }
  67797. break;
  67798. }
  67799. }
  67800. }
  67801. if (materialFound === false) {
  67802. loadedMaterialsIds.push(parsedMesh.materialId);
  67803. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67804. if (!mat) {
  67805. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67806. }
  67807. else {
  67808. log += "\n\tMaterial " + mat.toString(fullDetails);
  67809. }
  67810. }
  67811. }
  67812. // Skeleton ?
  67813. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67814. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67815. if (skeletonAlreadyLoaded === false) {
  67816. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67817. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67818. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67819. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67820. skeletons.push(skeleton);
  67821. loadedSkeletonsIds.push(parsedSkeleton.id);
  67822. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67823. }
  67824. }
  67825. }
  67826. }
  67827. // Morph targets ?
  67828. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67829. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67830. var managerData = _a[_i];
  67831. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67832. }
  67833. }
  67834. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67835. meshes.push(mesh);
  67836. log += "\n\tMesh " + mesh.toString(fullDetails);
  67837. }
  67838. }
  67839. // Connecting parents
  67840. var currentMesh;
  67841. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67842. currentMesh = scene.meshes[index];
  67843. if (currentMesh._waitingParentId) {
  67844. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67845. currentMesh._waitingParentId = null;
  67846. }
  67847. }
  67848. // freeze and compute world matrix application
  67849. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67850. currentMesh = scene.meshes[index];
  67851. if (currentMesh._waitingFreezeWorldMatrix) {
  67852. currentMesh.freezeWorldMatrix();
  67853. currentMesh._waitingFreezeWorldMatrix = null;
  67854. }
  67855. else {
  67856. currentMesh.computeWorldMatrix(true);
  67857. }
  67858. }
  67859. }
  67860. // Particles
  67861. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67862. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67863. var parsedParticleSystem = parsedData.particleSystems[index];
  67864. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67865. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67866. }
  67867. }
  67868. }
  67869. return true;
  67870. }
  67871. catch (err) {
  67872. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67873. if (onError) {
  67874. onError(msg, err);
  67875. }
  67876. else {
  67877. BABYLON.Tools.Log(msg);
  67878. throw err;
  67879. }
  67880. }
  67881. finally {
  67882. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67883. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67884. }
  67885. }
  67886. return false;
  67887. },
  67888. load: function (scene, data, rootUrl, onError) {
  67889. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67890. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67891. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67892. // and avoid problems with multiple concurrent .babylon loads.
  67893. var log = "importScene has failed JSON parse";
  67894. try {
  67895. var parsedData = JSON.parse(data);
  67896. log = "";
  67897. // Scene
  67898. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67899. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67900. }
  67901. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67902. scene.autoClear = parsedData.autoClear;
  67903. }
  67904. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67905. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67906. }
  67907. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67908. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67909. }
  67910. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67911. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67912. }
  67913. // Fog
  67914. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67915. scene.fogMode = parsedData.fogMode;
  67916. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67917. scene.fogStart = parsedData.fogStart;
  67918. scene.fogEnd = parsedData.fogEnd;
  67919. scene.fogDensity = parsedData.fogDensity;
  67920. log += "\tFog mode for scene: ";
  67921. switch (scene.fogMode) {
  67922. // getters not compiling, so using hardcoded
  67923. case 1:
  67924. log += "exp\n";
  67925. break;
  67926. case 2:
  67927. log += "exp2\n";
  67928. break;
  67929. case 3:
  67930. log += "linear\n";
  67931. break;
  67932. }
  67933. }
  67934. //Physics
  67935. if (parsedData.physicsEnabled) {
  67936. var physicsPlugin;
  67937. if (parsedData.physicsEngine === "cannon") {
  67938. physicsPlugin = new BABYLON.CannonJSPlugin();
  67939. }
  67940. else if (parsedData.physicsEngine === "oimo") {
  67941. physicsPlugin = new BABYLON.OimoJSPlugin();
  67942. }
  67943. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67944. //else - default engine, which is currently oimo
  67945. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67946. scene.enablePhysics(physicsGravity, physicsPlugin);
  67947. }
  67948. // Metadata
  67949. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67950. scene.metadata = parsedData.metadata;
  67951. }
  67952. //collisions, if defined. otherwise, default is true
  67953. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67954. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67955. }
  67956. scene.workerCollisions = !!parsedData.workerCollisions;
  67957. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67958. if (!container) {
  67959. return false;
  67960. }
  67961. if (parsedData.autoAnimate) {
  67962. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67963. }
  67964. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67965. scene.setActiveCameraByID(parsedData.activeCameraID);
  67966. }
  67967. // Environment texture
  67968. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67969. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67970. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67971. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67972. if (parsedData.environmentTextureRotationY) {
  67973. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67974. }
  67975. scene.environmentTexture = hdrTexture;
  67976. }
  67977. else {
  67978. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67979. if (parsedData.environmentTextureRotationY) {
  67980. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67981. }
  67982. scene.environmentTexture = cubeTexture;
  67983. }
  67984. if (parsedData.createDefaultSkybox === true) {
  67985. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67986. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67987. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67988. }
  67989. }
  67990. // Finish
  67991. return true;
  67992. }
  67993. catch (err) {
  67994. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67995. if (onError) {
  67996. onError(msg, err);
  67997. }
  67998. else {
  67999. BABYLON.Tools.Log(msg);
  68000. throw err;
  68001. }
  68002. }
  68003. finally {
  68004. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68005. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68006. }
  68007. }
  68008. return false;
  68009. },
  68010. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68011. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68012. return container;
  68013. }
  68014. });
  68015. })(BABYLON || (BABYLON = {}));
  68016. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68017. var BABYLON;
  68018. (function (BABYLON) {
  68019. var FilesInput = /** @class */ (function () {
  68020. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68021. this.onProcessFileCallback = function () { return true; };
  68022. this._engine = engine;
  68023. this._currentScene = scene;
  68024. this._sceneLoadedCallback = sceneLoadedCallback;
  68025. this._progressCallback = progressCallback;
  68026. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68027. this._textureLoadingCallback = textureLoadingCallback;
  68028. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68029. this._onReloadCallback = onReloadCallback;
  68030. this._errorCallback = errorCallback;
  68031. }
  68032. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68033. var _this = this;
  68034. if (elementToMonitor) {
  68035. this._elementToMonitor = elementToMonitor;
  68036. this._dragEnterHandler = function (e) { _this.drag(e); };
  68037. this._dragOverHandler = function (e) { _this.drag(e); };
  68038. this._dropHandler = function (e) { _this.drop(e); };
  68039. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68040. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68041. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68042. }
  68043. };
  68044. FilesInput.prototype.dispose = function () {
  68045. if (!this._elementToMonitor) {
  68046. return;
  68047. }
  68048. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68049. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68050. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68051. };
  68052. FilesInput.prototype.renderFunction = function () {
  68053. if (this._additionalRenderLoopLogicCallback) {
  68054. this._additionalRenderLoopLogicCallback();
  68055. }
  68056. if (this._currentScene) {
  68057. if (this._textureLoadingCallback) {
  68058. var remaining = this._currentScene.getWaitingItemsCount();
  68059. if (remaining > 0) {
  68060. this._textureLoadingCallback(remaining);
  68061. }
  68062. }
  68063. this._currentScene.render();
  68064. }
  68065. };
  68066. FilesInput.prototype.drag = function (e) {
  68067. e.stopPropagation();
  68068. e.preventDefault();
  68069. };
  68070. FilesInput.prototype.drop = function (eventDrop) {
  68071. eventDrop.stopPropagation();
  68072. eventDrop.preventDefault();
  68073. this.loadFiles(eventDrop);
  68074. };
  68075. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68076. var _this = this;
  68077. var reader = folder.createReader();
  68078. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68079. reader.readEntries(function (entries) {
  68080. remaining.count += entries.length;
  68081. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68082. var entry = entries_1[_i];
  68083. if (entry.isFile) {
  68084. entry.file(function (file) {
  68085. file.correctName = relativePath + file.name;
  68086. files.push(file);
  68087. if (--remaining.count === 0) {
  68088. callback();
  68089. }
  68090. });
  68091. }
  68092. else if (entry.isDirectory) {
  68093. _this._traverseFolder(entry, files, remaining, callback);
  68094. }
  68095. }
  68096. if (--remaining.count) {
  68097. callback();
  68098. }
  68099. });
  68100. };
  68101. FilesInput.prototype._processFiles = function (files) {
  68102. for (var i = 0; i < files.length; i++) {
  68103. var name = files[i].correctName.toLowerCase();
  68104. var extension = name.split('.').pop();
  68105. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68106. continue;
  68107. }
  68108. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68109. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68110. this._sceneFileToLoad = files[i];
  68111. }
  68112. else {
  68113. FilesInput.FilesToLoad[name] = files[i];
  68114. }
  68115. }
  68116. };
  68117. FilesInput.prototype.loadFiles = function (event) {
  68118. var _this = this;
  68119. if (this._startingProcessingFilesCallback)
  68120. this._startingProcessingFilesCallback();
  68121. // Handling data transfer via drag'n'drop
  68122. if (event && event.dataTransfer && event.dataTransfer.files) {
  68123. this._filesToLoad = event.dataTransfer.files;
  68124. }
  68125. // Handling files from input files
  68126. if (event && event.target && event.target.files) {
  68127. this._filesToLoad = event.target.files;
  68128. }
  68129. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68130. var files_1 = new Array();
  68131. var folders = [];
  68132. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68133. for (var i = 0; i < this._filesToLoad.length; i++) {
  68134. var fileToLoad = this._filesToLoad[i];
  68135. var name_1 = fileToLoad.name.toLowerCase();
  68136. var entry = void 0;
  68137. fileToLoad.correctName = name_1;
  68138. if (items) {
  68139. var item = items[i];
  68140. if (item.getAsEntry) {
  68141. entry = item.getAsEntry();
  68142. }
  68143. else if (item.webkitGetAsEntry) {
  68144. entry = item.webkitGetAsEntry();
  68145. }
  68146. }
  68147. if (!entry) {
  68148. files_1.push(fileToLoad);
  68149. }
  68150. else {
  68151. if (entry.isDirectory) {
  68152. folders.push(entry);
  68153. }
  68154. else {
  68155. files_1.push(fileToLoad);
  68156. }
  68157. }
  68158. }
  68159. if (folders.length === 0) {
  68160. this._processFiles(files_1);
  68161. this._processReload();
  68162. }
  68163. else {
  68164. var remaining = { count: folders.length };
  68165. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68166. var folder = folders_1[_i];
  68167. this._traverseFolder(folder, files_1, remaining, function () {
  68168. _this._processFiles(files_1);
  68169. if (remaining.count === 0) {
  68170. _this._processReload();
  68171. }
  68172. });
  68173. }
  68174. }
  68175. }
  68176. };
  68177. FilesInput.prototype._processReload = function () {
  68178. if (this._onReloadCallback) {
  68179. this._onReloadCallback(this._sceneFileToLoad);
  68180. }
  68181. else {
  68182. this.reload();
  68183. }
  68184. };
  68185. FilesInput.prototype.reload = function () {
  68186. var _this = this;
  68187. // If a scene file has been provided
  68188. if (this._sceneFileToLoad) {
  68189. if (this._currentScene) {
  68190. if (BABYLON.Tools.errorsCount > 0) {
  68191. BABYLON.Tools.ClearLogCache();
  68192. }
  68193. this._engine.stopRenderLoop();
  68194. this._currentScene.dispose();
  68195. }
  68196. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68197. if (_this._progressCallback) {
  68198. _this._progressCallback(progress);
  68199. }
  68200. }).then(function (scene) {
  68201. _this._currentScene = scene;
  68202. if (_this._sceneLoadedCallback) {
  68203. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68204. }
  68205. // Wait for textures and shaders to be ready
  68206. _this._currentScene.executeWhenReady(function () {
  68207. _this._engine.runRenderLoop(function () {
  68208. _this.renderFunction();
  68209. });
  68210. });
  68211. }).catch(function (error) {
  68212. if (_this._errorCallback) {
  68213. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68214. }
  68215. });
  68216. }
  68217. else {
  68218. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68219. }
  68220. };
  68221. FilesInput.FilesToLoad = {};
  68222. return FilesInput;
  68223. }());
  68224. BABYLON.FilesInput = FilesInput;
  68225. })(BABYLON || (BABYLON = {}));
  68226. //# sourceMappingURL=babylon.filesInput.js.map
  68227. var BABYLON;
  68228. (function (BABYLON) {
  68229. /**
  68230. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68231. * The underlying implementation relies on an associative array to ensure the best performances.
  68232. * The value can be anything including 'null' but except 'undefined'
  68233. */
  68234. var StringDictionary = /** @class */ (function () {
  68235. function StringDictionary() {
  68236. this._count = 0;
  68237. this._data = {};
  68238. }
  68239. /**
  68240. * This will clear this dictionary and copy the content from the 'source' one.
  68241. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68242. * @param source the dictionary to take the content from and copy to this dictionary
  68243. */
  68244. StringDictionary.prototype.copyFrom = function (source) {
  68245. var _this = this;
  68246. this.clear();
  68247. source.forEach(function (t, v) { return _this.add(t, v); });
  68248. };
  68249. /**
  68250. * Get a value based from its key
  68251. * @param key the given key to get the matching value from
  68252. * @return the value if found, otherwise undefined is returned
  68253. */
  68254. StringDictionary.prototype.get = function (key) {
  68255. var val = this._data[key];
  68256. if (val !== undefined) {
  68257. return val;
  68258. }
  68259. return undefined;
  68260. };
  68261. /**
  68262. * Get a value from its key or add it if it doesn't exist.
  68263. * This method will ensure you that a given key/data will be present in the dictionary.
  68264. * @param key the given key to get the matching value from
  68265. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68266. * The factory will only be invoked if there's no data for the given key.
  68267. * @return the value corresponding to the key.
  68268. */
  68269. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68270. var val = this.get(key);
  68271. if (val !== undefined) {
  68272. return val;
  68273. }
  68274. val = factory(key);
  68275. if (val) {
  68276. this.add(key, val);
  68277. }
  68278. return val;
  68279. };
  68280. /**
  68281. * Get a value from its key if present in the dictionary otherwise add it
  68282. * @param key the key to get the value from
  68283. * @param val if there's no such key/value pair in the dictionary add it with this value
  68284. * @return the value corresponding to the key
  68285. */
  68286. StringDictionary.prototype.getOrAdd = function (key, val) {
  68287. var curVal = this.get(key);
  68288. if (curVal !== undefined) {
  68289. return curVal;
  68290. }
  68291. this.add(key, val);
  68292. return val;
  68293. };
  68294. /**
  68295. * Check if there's a given key in the dictionary
  68296. * @param key the key to check for
  68297. * @return true if the key is present, false otherwise
  68298. */
  68299. StringDictionary.prototype.contains = function (key) {
  68300. return this._data[key] !== undefined;
  68301. };
  68302. /**
  68303. * Add a new key and its corresponding value
  68304. * @param key the key to add
  68305. * @param value the value corresponding to the key
  68306. * @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
  68307. */
  68308. StringDictionary.prototype.add = function (key, value) {
  68309. if (this._data[key] !== undefined) {
  68310. return false;
  68311. }
  68312. this._data[key] = value;
  68313. ++this._count;
  68314. return true;
  68315. };
  68316. StringDictionary.prototype.set = function (key, value) {
  68317. if (this._data[key] === undefined) {
  68318. return false;
  68319. }
  68320. this._data[key] = value;
  68321. return true;
  68322. };
  68323. /**
  68324. * Get the element of the given key and remove it from the dictionary
  68325. * @param key
  68326. */
  68327. StringDictionary.prototype.getAndRemove = function (key) {
  68328. var val = this.get(key);
  68329. if (val !== undefined) {
  68330. delete this._data[key];
  68331. --this._count;
  68332. return val;
  68333. }
  68334. return null;
  68335. };
  68336. /**
  68337. * Remove a key/value from the dictionary.
  68338. * @param key the key to remove
  68339. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68340. */
  68341. StringDictionary.prototype.remove = function (key) {
  68342. if (this.contains(key)) {
  68343. delete this._data[key];
  68344. --this._count;
  68345. return true;
  68346. }
  68347. return false;
  68348. };
  68349. /**
  68350. * Clear the whole content of the dictionary
  68351. */
  68352. StringDictionary.prototype.clear = function () {
  68353. this._data = {};
  68354. this._count = 0;
  68355. };
  68356. Object.defineProperty(StringDictionary.prototype, "count", {
  68357. get: function () {
  68358. return this._count;
  68359. },
  68360. enumerable: true,
  68361. configurable: true
  68362. });
  68363. /**
  68364. * Execute a callback on each key/val of the dictionary.
  68365. * Note that you can remove any element in this dictionary in the callback implementation
  68366. * @param callback the callback to execute on a given key/value pair
  68367. */
  68368. StringDictionary.prototype.forEach = function (callback) {
  68369. for (var cur in this._data) {
  68370. var val = this._data[cur];
  68371. callback(cur, val);
  68372. }
  68373. };
  68374. /**
  68375. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68376. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68377. * Note that you can remove any element in this dictionary in the callback implementation
  68378. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68379. */
  68380. StringDictionary.prototype.first = function (callback) {
  68381. for (var cur in this._data) {
  68382. var val = this._data[cur];
  68383. var res = callback(cur, val);
  68384. if (res) {
  68385. return res;
  68386. }
  68387. }
  68388. return null;
  68389. };
  68390. return StringDictionary;
  68391. }());
  68392. BABYLON.StringDictionary = StringDictionary;
  68393. })(BABYLON || (BABYLON = {}));
  68394. //# sourceMappingURL=babylon.stringDictionary.js.map
  68395. var BABYLON;
  68396. (function (BABYLON) {
  68397. var Tags = /** @class */ (function () {
  68398. function Tags() {
  68399. }
  68400. Tags.EnableFor = function (obj) {
  68401. obj._tags = obj._tags || {};
  68402. obj.hasTags = function () {
  68403. return Tags.HasTags(obj);
  68404. };
  68405. obj.addTags = function (tagsString) {
  68406. return Tags.AddTagsTo(obj, tagsString);
  68407. };
  68408. obj.removeTags = function (tagsString) {
  68409. return Tags.RemoveTagsFrom(obj, tagsString);
  68410. };
  68411. obj.matchesTagsQuery = function (tagsQuery) {
  68412. return Tags.MatchesQuery(obj, tagsQuery);
  68413. };
  68414. };
  68415. Tags.DisableFor = function (obj) {
  68416. delete obj._tags;
  68417. delete obj.hasTags;
  68418. delete obj.addTags;
  68419. delete obj.removeTags;
  68420. delete obj.matchesTagsQuery;
  68421. };
  68422. Tags.HasTags = function (obj) {
  68423. if (!obj._tags) {
  68424. return false;
  68425. }
  68426. return !BABYLON.Tools.IsEmpty(obj._tags);
  68427. };
  68428. Tags.GetTags = function (obj, asString) {
  68429. if (asString === void 0) { asString = true; }
  68430. if (!obj._tags) {
  68431. return null;
  68432. }
  68433. if (asString) {
  68434. var tagsArray = [];
  68435. for (var tag in obj._tags) {
  68436. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68437. tagsArray.push(tag);
  68438. }
  68439. }
  68440. return tagsArray.join(" ");
  68441. }
  68442. else {
  68443. return obj._tags;
  68444. }
  68445. };
  68446. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68447. // a tag cannot start with '||', '&&', and '!'
  68448. // it cannot contain whitespaces
  68449. Tags.AddTagsTo = function (obj, tagsString) {
  68450. if (!tagsString) {
  68451. return;
  68452. }
  68453. if (typeof tagsString !== "string") {
  68454. return;
  68455. }
  68456. var tags = tagsString.split(" ");
  68457. tags.forEach(function (tag, index, array) {
  68458. Tags._AddTagTo(obj, tag);
  68459. });
  68460. };
  68461. Tags._AddTagTo = function (obj, tag) {
  68462. tag = tag.trim();
  68463. if (tag === "" || tag === "true" || tag === "false") {
  68464. return;
  68465. }
  68466. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68467. return;
  68468. }
  68469. Tags.EnableFor(obj);
  68470. obj._tags[tag] = true;
  68471. };
  68472. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68473. if (!Tags.HasTags(obj)) {
  68474. return;
  68475. }
  68476. var tags = tagsString.split(" ");
  68477. for (var t in tags) {
  68478. Tags._RemoveTagFrom(obj, tags[t]);
  68479. }
  68480. };
  68481. Tags._RemoveTagFrom = function (obj, tag) {
  68482. delete obj._tags[tag];
  68483. };
  68484. Tags.MatchesQuery = function (obj, tagsQuery) {
  68485. if (tagsQuery === undefined) {
  68486. return true;
  68487. }
  68488. if (tagsQuery === "") {
  68489. return Tags.HasTags(obj);
  68490. }
  68491. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68492. };
  68493. return Tags;
  68494. }());
  68495. BABYLON.Tags = Tags;
  68496. })(BABYLON || (BABYLON = {}));
  68497. //# sourceMappingURL=babylon.tags.js.map
  68498. var BABYLON;
  68499. (function (BABYLON) {
  68500. /**
  68501. * Class used to evalaute queries containing `and` and `or` operators
  68502. */
  68503. var AndOrNotEvaluator = /** @class */ (function () {
  68504. function AndOrNotEvaluator() {
  68505. }
  68506. /**
  68507. * Evaluate a query
  68508. * @param query defines the query to evaluate
  68509. * @param evaluateCallback defines the callback used to filter result
  68510. * @returns true if the query matches
  68511. */
  68512. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68513. if (!query.match(/\([^\(\)]*\)/g)) {
  68514. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68515. }
  68516. else {
  68517. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68518. // remove parenthesis
  68519. r = r.slice(1, r.length - 1);
  68520. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68521. });
  68522. }
  68523. if (query === "true") {
  68524. return true;
  68525. }
  68526. if (query === "false") {
  68527. return false;
  68528. }
  68529. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68530. };
  68531. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68532. evaluateCallback = evaluateCallback || (function (r) {
  68533. return r === "true" ? true : false;
  68534. });
  68535. var result;
  68536. var or = parenthesisContent.split("||");
  68537. for (var i in or) {
  68538. if (or.hasOwnProperty(i)) {
  68539. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68540. var and = ori.split("&&");
  68541. if (and.length > 1) {
  68542. for (var j = 0; j < and.length; ++j) {
  68543. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68544. if (andj !== "true" && andj !== "false") {
  68545. if (andj[0] === "!") {
  68546. result = !evaluateCallback(andj.substring(1));
  68547. }
  68548. else {
  68549. result = evaluateCallback(andj);
  68550. }
  68551. }
  68552. else {
  68553. result = andj === "true" ? true : false;
  68554. }
  68555. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68556. ori = "false";
  68557. break;
  68558. }
  68559. }
  68560. }
  68561. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68562. result = true;
  68563. break;
  68564. }
  68565. // result equals false (or undefined)
  68566. if (ori !== "true" && ori !== "false") {
  68567. if (ori[0] === "!") {
  68568. result = !evaluateCallback(ori.substring(1));
  68569. }
  68570. else {
  68571. result = evaluateCallback(ori);
  68572. }
  68573. }
  68574. else {
  68575. result = ori === "true" ? true : false;
  68576. }
  68577. }
  68578. }
  68579. // the whole parenthesis scope is replaced by 'true' or 'false'
  68580. return result ? "true" : "false";
  68581. };
  68582. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68583. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68584. // remove whitespaces
  68585. r = r.replace(/[\s]/g, function () { return ""; });
  68586. return r.length % 2 ? "!" : "";
  68587. });
  68588. booleanString = booleanString.trim();
  68589. if (booleanString === "!true") {
  68590. booleanString = "false";
  68591. }
  68592. else if (booleanString === "!false") {
  68593. booleanString = "true";
  68594. }
  68595. return booleanString;
  68596. };
  68597. return AndOrNotEvaluator;
  68598. }());
  68599. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68600. })(BABYLON || (BABYLON = {}));
  68601. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68602. var BABYLON;
  68603. (function (BABYLON) {
  68604. /**
  68605. * Class used to enable access to IndexedDB
  68606. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68607. */
  68608. var Database = /** @class */ (function () {
  68609. /**
  68610. * Creates a new Database
  68611. * @param urlToScene defines the url to load the scene
  68612. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68613. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68614. */
  68615. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68616. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68617. var _this = this;
  68618. // Handling various flavors of prefixed version of IndexedDB
  68619. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68620. this.callbackManifestChecked = callbackManifestChecked;
  68621. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68622. this.db = null;
  68623. this._enableSceneOffline = false;
  68624. this._enableTexturesOffline = false;
  68625. this.manifestVersionFound = 0;
  68626. this.mustUpdateRessources = false;
  68627. this.hasReachedQuota = false;
  68628. if (!Database.IDBStorageEnabled) {
  68629. this.callbackManifestChecked(true);
  68630. }
  68631. else {
  68632. if (disableManifestCheck) {
  68633. this._enableSceneOffline = true;
  68634. this._enableTexturesOffline = true;
  68635. this.manifestVersionFound = 1;
  68636. BABYLON.Tools.SetImmediate(function () {
  68637. _this.callbackManifestChecked(true);
  68638. });
  68639. }
  68640. else {
  68641. this._checkManifestFile();
  68642. }
  68643. }
  68644. }
  68645. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68646. /**
  68647. * Gets a boolean indicating if scene must be saved in the database
  68648. */
  68649. get: function () {
  68650. return this._enableSceneOffline;
  68651. },
  68652. enumerable: true,
  68653. configurable: true
  68654. });
  68655. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68656. /**
  68657. * Gets a boolean indicating if textures must be saved in the database
  68658. */
  68659. get: function () {
  68660. return this._enableTexturesOffline;
  68661. },
  68662. enumerable: true,
  68663. configurable: true
  68664. });
  68665. Database.prototype._checkManifestFile = function () {
  68666. var _this = this;
  68667. var noManifestFile = function () {
  68668. _this._enableSceneOffline = false;
  68669. _this._enableTexturesOffline = false;
  68670. _this.callbackManifestChecked(false);
  68671. };
  68672. var timeStampUsed = false;
  68673. var manifestURL = this.currentSceneUrl + ".manifest";
  68674. var xhr = new XMLHttpRequest();
  68675. if (navigator.onLine) {
  68676. // Adding a timestamp to by-pass browsers' cache
  68677. timeStampUsed = true;
  68678. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68679. }
  68680. xhr.open("GET", manifestURL, true);
  68681. xhr.addEventListener("load", function () {
  68682. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68683. try {
  68684. var manifestFile = JSON.parse(xhr.response);
  68685. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68686. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68687. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68688. _this.manifestVersionFound = manifestFile.version;
  68689. }
  68690. if (_this.callbackManifestChecked) {
  68691. _this.callbackManifestChecked(true);
  68692. }
  68693. }
  68694. catch (ex) {
  68695. noManifestFile();
  68696. }
  68697. }
  68698. else {
  68699. noManifestFile();
  68700. }
  68701. }, false);
  68702. xhr.addEventListener("error", function (event) {
  68703. if (timeStampUsed) {
  68704. timeStampUsed = false;
  68705. // Let's retry without the timeStamp
  68706. // It could fail when coupled with HTML5 Offline API
  68707. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68708. xhr.open("GET", retryManifestURL, true);
  68709. xhr.send();
  68710. }
  68711. else {
  68712. noManifestFile();
  68713. }
  68714. }, false);
  68715. try {
  68716. xhr.send();
  68717. }
  68718. catch (ex) {
  68719. BABYLON.Tools.Error("Error on XHR send request.");
  68720. this.callbackManifestChecked(false);
  68721. }
  68722. };
  68723. /**
  68724. * Open the database and make it available
  68725. * @param successCallback defines the callback to call on success
  68726. * @param errorCallback defines the callback to call on error
  68727. */
  68728. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68729. var _this = this;
  68730. var handleError = function () {
  68731. _this.isSupported = false;
  68732. if (errorCallback)
  68733. errorCallback();
  68734. };
  68735. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68736. // Your browser doesn't support IndexedDB
  68737. this.isSupported = false;
  68738. if (errorCallback)
  68739. errorCallback();
  68740. }
  68741. else {
  68742. // If the DB hasn't been opened or created yet
  68743. if (!this.db) {
  68744. this.hasReachedQuota = false;
  68745. this.isSupported = true;
  68746. var request = this.idbFactory.open("babylonjs", 1);
  68747. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68748. request.onerror = function (event) {
  68749. handleError();
  68750. };
  68751. // executes when a version change transaction cannot complete due to other active transactions
  68752. request.onblocked = function (event) {
  68753. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68754. handleError();
  68755. };
  68756. // DB has been opened successfully
  68757. request.onsuccess = function (event) {
  68758. _this.db = request.result;
  68759. successCallback();
  68760. };
  68761. // Initialization of the DB. Creating Scenes & Textures stores
  68762. request.onupgradeneeded = function (event) {
  68763. _this.db = (event.target).result;
  68764. if (_this.db) {
  68765. try {
  68766. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68767. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68768. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68769. }
  68770. catch (ex) {
  68771. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68772. handleError();
  68773. }
  68774. }
  68775. };
  68776. }
  68777. // DB has already been created and opened
  68778. else {
  68779. if (successCallback)
  68780. successCallback();
  68781. }
  68782. }
  68783. };
  68784. /**
  68785. * Loads an image from the database
  68786. * @param url defines the url to load from
  68787. * @param image defines the target DOM image
  68788. */
  68789. Database.prototype.loadImageFromDB = function (url, image) {
  68790. var _this = this;
  68791. var completeURL = Database._ReturnFullUrlLocation(url);
  68792. var saveAndLoadImage = function () {
  68793. if (!_this.hasReachedQuota && _this.db !== null) {
  68794. // the texture is not yet in the DB, let's try to save it
  68795. _this._saveImageIntoDBAsync(completeURL, image);
  68796. }
  68797. // If the texture is not in the DB and we've reached the DB quota limit
  68798. // let's load it directly from the web
  68799. else {
  68800. image.src = url;
  68801. }
  68802. };
  68803. if (!this.mustUpdateRessources) {
  68804. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68805. }
  68806. // First time we're download the images or update requested in the manifest file by a version change
  68807. else {
  68808. saveAndLoadImage();
  68809. }
  68810. };
  68811. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68812. if (this.isSupported && this.db !== null) {
  68813. var texture;
  68814. var transaction = this.db.transaction(["textures"]);
  68815. transaction.onabort = function (event) {
  68816. image.src = url;
  68817. };
  68818. transaction.oncomplete = function (event) {
  68819. var blobTextureURL;
  68820. if (texture) {
  68821. var URL = window.URL || window.webkitURL;
  68822. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68823. image.onerror = function () {
  68824. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68825. image.src = url;
  68826. };
  68827. image.src = blobTextureURL;
  68828. }
  68829. else {
  68830. notInDBCallback();
  68831. }
  68832. };
  68833. var getRequest = transaction.objectStore("textures").get(url);
  68834. getRequest.onsuccess = function (event) {
  68835. texture = (event.target).result;
  68836. };
  68837. getRequest.onerror = function (event) {
  68838. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68839. image.src = url;
  68840. };
  68841. }
  68842. else {
  68843. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68844. image.src = url;
  68845. }
  68846. };
  68847. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68848. var _this = this;
  68849. if (this.isSupported) {
  68850. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68851. var generateBlobUrl = function () {
  68852. var blobTextureURL;
  68853. if (blob) {
  68854. var URL = window.URL || window.webkitURL;
  68855. try {
  68856. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68857. }
  68858. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68859. catch (ex) {
  68860. blobTextureURL = URL.createObjectURL(blob);
  68861. }
  68862. }
  68863. if (blobTextureURL) {
  68864. image.src = blobTextureURL;
  68865. }
  68866. };
  68867. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68868. var xhr = new XMLHttpRequest(), blob;
  68869. xhr.open("GET", url, true);
  68870. xhr.responseType = "blob";
  68871. xhr.addEventListener("load", function () {
  68872. if (xhr.status === 200 && _this.db) {
  68873. // Blob as response (XHR2)
  68874. blob = xhr.response;
  68875. var transaction = _this.db.transaction(["textures"], "readwrite");
  68876. // the transaction could abort because of a QuotaExceededError error
  68877. transaction.onabort = function (event) {
  68878. try {
  68879. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68880. var srcElement = (event.srcElement || event.target);
  68881. var error = srcElement.error;
  68882. if (error && error.name === "QuotaExceededError") {
  68883. _this.hasReachedQuota = true;
  68884. }
  68885. }
  68886. catch (ex) { }
  68887. generateBlobUrl();
  68888. };
  68889. transaction.oncomplete = function (event) {
  68890. generateBlobUrl();
  68891. };
  68892. var newTexture = { textureUrl: url, data: blob };
  68893. try {
  68894. // Put the blob into the dabase
  68895. var addRequest = transaction.objectStore("textures").put(newTexture);
  68896. addRequest.onsuccess = function (event) {
  68897. };
  68898. addRequest.onerror = function (event) {
  68899. generateBlobUrl();
  68900. };
  68901. }
  68902. catch (ex) {
  68903. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68904. if (ex.code === 25) {
  68905. Database.IsUASupportingBlobStorage = false;
  68906. }
  68907. image.src = url;
  68908. }
  68909. }
  68910. else {
  68911. image.src = url;
  68912. }
  68913. }, false);
  68914. xhr.addEventListener("error", function (event) {
  68915. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68916. image.src = url;
  68917. }, false);
  68918. xhr.send();
  68919. }
  68920. else {
  68921. image.src = url;
  68922. }
  68923. }
  68924. else {
  68925. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68926. image.src = url;
  68927. }
  68928. };
  68929. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68930. var _this = this;
  68931. var updateVersion = function () {
  68932. // the version is not yet in the DB or we need to update it
  68933. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68934. };
  68935. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68936. };
  68937. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68938. var _this = this;
  68939. if (this.isSupported && this.db) {
  68940. var version;
  68941. try {
  68942. var transaction = this.db.transaction(["versions"]);
  68943. transaction.oncomplete = function (event) {
  68944. if (version) {
  68945. // If the version in the JSON file is different from the version in DB
  68946. if (_this.manifestVersionFound !== version.data) {
  68947. _this.mustUpdateRessources = true;
  68948. updateInDBCallback();
  68949. }
  68950. else {
  68951. callback(version.data);
  68952. }
  68953. }
  68954. // version was not found in DB
  68955. else {
  68956. _this.mustUpdateRessources = true;
  68957. updateInDBCallback();
  68958. }
  68959. };
  68960. transaction.onabort = function (event) {
  68961. callback(-1);
  68962. };
  68963. var getRequest = transaction.objectStore("versions").get(url);
  68964. getRequest.onsuccess = function (event) {
  68965. version = (event.target).result;
  68966. };
  68967. getRequest.onerror = function (event) {
  68968. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68969. callback(-1);
  68970. };
  68971. }
  68972. catch (ex) {
  68973. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68974. callback(-1);
  68975. }
  68976. }
  68977. else {
  68978. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68979. callback(-1);
  68980. }
  68981. };
  68982. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68983. var _this = this;
  68984. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68985. try {
  68986. // Open a transaction to the database
  68987. var transaction = this.db.transaction(["versions"], "readwrite");
  68988. // the transaction could abort because of a QuotaExceededError error
  68989. transaction.onabort = function (event) {
  68990. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68991. var error = event.srcElement['error'];
  68992. if (error && error.name === "QuotaExceededError") {
  68993. _this.hasReachedQuota = true;
  68994. }
  68995. }
  68996. catch (ex) { }
  68997. callback(-1);
  68998. };
  68999. transaction.oncomplete = function (event) {
  69000. callback(_this.manifestVersionFound);
  69001. };
  69002. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69003. // Put the scene into the database
  69004. var addRequest = transaction.objectStore("versions").put(newVersion);
  69005. addRequest.onsuccess = function (event) {
  69006. };
  69007. addRequest.onerror = function (event) {
  69008. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69009. };
  69010. }
  69011. catch (ex) {
  69012. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69013. callback(-1);
  69014. }
  69015. }
  69016. else {
  69017. callback(-1);
  69018. }
  69019. };
  69020. /**
  69021. * Loads a file from database
  69022. * @param url defines the URL to load from
  69023. * @param sceneLoaded defines a callback to call on success
  69024. * @param progressCallBack defines a callback to call when progress changed
  69025. * @param errorCallback defines a callback to call on error
  69026. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69027. */
  69028. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69029. var _this = this;
  69030. var completeUrl = Database._ReturnFullUrlLocation(url);
  69031. var saveAndLoadFile = function () {
  69032. // the scene is not yet in the DB, let's try to save it
  69033. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69034. };
  69035. this._checkVersionFromDB(completeUrl, function (version) {
  69036. if (version !== -1) {
  69037. if (!_this.mustUpdateRessources) {
  69038. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69039. }
  69040. else {
  69041. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69042. }
  69043. }
  69044. else {
  69045. if (errorCallback) {
  69046. errorCallback();
  69047. }
  69048. }
  69049. });
  69050. };
  69051. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69052. if (this.isSupported && this.db) {
  69053. var targetStore;
  69054. if (url.indexOf(".babylon") !== -1) {
  69055. targetStore = "scenes";
  69056. }
  69057. else {
  69058. targetStore = "textures";
  69059. }
  69060. var file;
  69061. var transaction = this.db.transaction([targetStore]);
  69062. transaction.oncomplete = function (event) {
  69063. if (file) {
  69064. callback(file.data);
  69065. }
  69066. // file was not found in DB
  69067. else {
  69068. notInDBCallback();
  69069. }
  69070. };
  69071. transaction.onabort = function (event) {
  69072. notInDBCallback();
  69073. };
  69074. var getRequest = transaction.objectStore(targetStore).get(url);
  69075. getRequest.onsuccess = function (event) {
  69076. file = (event.target).result;
  69077. };
  69078. getRequest.onerror = function (event) {
  69079. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69080. notInDBCallback();
  69081. };
  69082. }
  69083. else {
  69084. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69085. callback();
  69086. }
  69087. };
  69088. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69089. var _this = this;
  69090. if (this.isSupported) {
  69091. var targetStore;
  69092. if (url.indexOf(".babylon") !== -1) {
  69093. targetStore = "scenes";
  69094. }
  69095. else {
  69096. targetStore = "textures";
  69097. }
  69098. // Create XHR
  69099. var xhr = new XMLHttpRequest();
  69100. var fileData;
  69101. xhr.open("GET", url, true);
  69102. if (useArrayBuffer) {
  69103. xhr.responseType = "arraybuffer";
  69104. }
  69105. if (progressCallback) {
  69106. xhr.onprogress = progressCallback;
  69107. }
  69108. xhr.addEventListener("load", function () {
  69109. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69110. // Blob as response (XHR2)
  69111. //fileData = xhr.responseText;
  69112. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69113. if (!_this.hasReachedQuota && _this.db) {
  69114. // Open a transaction to the database
  69115. var transaction = _this.db.transaction([targetStore], "readwrite");
  69116. // the transaction could abort because of a QuotaExceededError error
  69117. transaction.onabort = function (event) {
  69118. try {
  69119. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69120. var error = event.srcElement['error'];
  69121. if (error && error.name === "QuotaExceededError") {
  69122. _this.hasReachedQuota = true;
  69123. }
  69124. }
  69125. catch (ex) { }
  69126. callback(fileData);
  69127. };
  69128. transaction.oncomplete = function (event) {
  69129. callback(fileData);
  69130. };
  69131. var newFile;
  69132. if (targetStore === "scenes") {
  69133. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69134. }
  69135. else {
  69136. newFile = { textureUrl: url, data: fileData };
  69137. }
  69138. try {
  69139. // Put the scene into the database
  69140. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69141. addRequest.onsuccess = function (event) {
  69142. };
  69143. addRequest.onerror = function (event) {
  69144. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69145. };
  69146. }
  69147. catch (ex) {
  69148. callback(fileData);
  69149. }
  69150. }
  69151. else {
  69152. callback(fileData);
  69153. }
  69154. }
  69155. else {
  69156. callback();
  69157. }
  69158. }, false);
  69159. xhr.addEventListener("error", function (event) {
  69160. BABYLON.Tools.Error("error on XHR request.");
  69161. callback();
  69162. }, false);
  69163. xhr.send();
  69164. }
  69165. else {
  69166. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69167. callback();
  69168. }
  69169. };
  69170. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69171. Database.IsUASupportingBlobStorage = true;
  69172. /** Gets a boolean indicating if Database storate is enabled */
  69173. Database.IDBStorageEnabled = true;
  69174. Database._ParseURL = function (url) {
  69175. var a = document.createElement('a');
  69176. a.href = url;
  69177. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69178. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69179. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69180. return absLocation;
  69181. };
  69182. Database._ReturnFullUrlLocation = function (url) {
  69183. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69184. return (Database._ParseURL(window.location.href) + url);
  69185. }
  69186. else {
  69187. return url;
  69188. }
  69189. };
  69190. return Database;
  69191. }());
  69192. BABYLON.Database = Database;
  69193. })(BABYLON || (BABYLON = {}));
  69194. //# sourceMappingURL=babylon.database.js.map
  69195. var BABYLON;
  69196. (function (BABYLON) {
  69197. var FresnelParameters = /** @class */ (function () {
  69198. function FresnelParameters() {
  69199. this._isEnabled = true;
  69200. this.leftColor = BABYLON.Color3.White();
  69201. this.rightColor = BABYLON.Color3.Black();
  69202. this.bias = 0;
  69203. this.power = 1;
  69204. }
  69205. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69206. get: function () {
  69207. return this._isEnabled;
  69208. },
  69209. set: function (value) {
  69210. if (this._isEnabled === value) {
  69211. return;
  69212. }
  69213. this._isEnabled = value;
  69214. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69215. },
  69216. enumerable: true,
  69217. configurable: true
  69218. });
  69219. FresnelParameters.prototype.clone = function () {
  69220. var newFresnelParameters = new FresnelParameters();
  69221. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69222. return newFresnelParameters;
  69223. };
  69224. FresnelParameters.prototype.serialize = function () {
  69225. var serializationObject = {};
  69226. serializationObject.isEnabled = this.isEnabled;
  69227. serializationObject.leftColor = this.leftColor.asArray();
  69228. serializationObject.rightColor = this.rightColor.asArray();
  69229. serializationObject.bias = this.bias;
  69230. serializationObject.power = this.power;
  69231. return serializationObject;
  69232. };
  69233. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69234. var fresnelParameters = new FresnelParameters();
  69235. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69236. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69237. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69238. fresnelParameters.bias = parsedFresnelParameters.bias;
  69239. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69240. return fresnelParameters;
  69241. };
  69242. return FresnelParameters;
  69243. }());
  69244. BABYLON.FresnelParameters = FresnelParameters;
  69245. })(BABYLON || (BABYLON = {}));
  69246. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69247. var BABYLON;
  69248. (function (BABYLON) {
  69249. var MultiMaterial = /** @class */ (function (_super) {
  69250. __extends(MultiMaterial, _super);
  69251. function MultiMaterial(name, scene) {
  69252. var _this = _super.call(this, name, scene, true) || this;
  69253. scene.multiMaterials.push(_this);
  69254. _this.subMaterials = new Array();
  69255. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69256. return _this;
  69257. }
  69258. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69259. get: function () {
  69260. return this._subMaterials;
  69261. },
  69262. set: function (value) {
  69263. this._subMaterials = value;
  69264. this._hookArray(value);
  69265. },
  69266. enumerable: true,
  69267. configurable: true
  69268. });
  69269. MultiMaterial.prototype._hookArray = function (array) {
  69270. var _this = this;
  69271. var oldPush = array.push;
  69272. array.push = function () {
  69273. var items = [];
  69274. for (var _i = 0; _i < arguments.length; _i++) {
  69275. items[_i] = arguments[_i];
  69276. }
  69277. var result = oldPush.apply(array, items);
  69278. _this._markAllSubMeshesAsTexturesDirty();
  69279. return result;
  69280. };
  69281. var oldSplice = array.splice;
  69282. array.splice = function (index, deleteCount) {
  69283. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69284. _this._markAllSubMeshesAsTexturesDirty();
  69285. return deleted;
  69286. };
  69287. };
  69288. // Properties
  69289. MultiMaterial.prototype.getSubMaterial = function (index) {
  69290. if (index < 0 || index >= this.subMaterials.length) {
  69291. return this.getScene().defaultMaterial;
  69292. }
  69293. return this.subMaterials[index];
  69294. };
  69295. MultiMaterial.prototype.getActiveTextures = function () {
  69296. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69297. if (subMaterial) {
  69298. return subMaterial.getActiveTextures();
  69299. }
  69300. else {
  69301. return [];
  69302. }
  69303. }));
  69304. var _a;
  69305. };
  69306. // Methods
  69307. MultiMaterial.prototype.getClassName = function () {
  69308. return "MultiMaterial";
  69309. };
  69310. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69311. for (var index = 0; index < this.subMaterials.length; index++) {
  69312. var subMaterial = this.subMaterials[index];
  69313. if (subMaterial) {
  69314. if (subMaterial.storeEffectOnSubMeshes) {
  69315. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69316. return false;
  69317. }
  69318. continue;
  69319. }
  69320. if (!subMaterial.isReady(mesh)) {
  69321. return false;
  69322. }
  69323. }
  69324. }
  69325. return true;
  69326. };
  69327. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69328. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69329. for (var index = 0; index < this.subMaterials.length; index++) {
  69330. var subMaterial = null;
  69331. var current = this.subMaterials[index];
  69332. if (cloneChildren && current) {
  69333. subMaterial = current.clone(name + "-" + current.name);
  69334. }
  69335. else {
  69336. subMaterial = this.subMaterials[index];
  69337. }
  69338. newMultiMaterial.subMaterials.push(subMaterial);
  69339. }
  69340. return newMultiMaterial;
  69341. };
  69342. MultiMaterial.prototype.serialize = function () {
  69343. var serializationObject = {};
  69344. serializationObject.name = this.name;
  69345. serializationObject.id = this.id;
  69346. if (BABYLON.Tags) {
  69347. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69348. }
  69349. serializationObject.materials = [];
  69350. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69351. var subMat = this.subMaterials[matIndex];
  69352. if (subMat) {
  69353. serializationObject.materials.push(subMat.id);
  69354. }
  69355. else {
  69356. serializationObject.materials.push(null);
  69357. }
  69358. }
  69359. return serializationObject;
  69360. };
  69361. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69362. var scene = this.getScene();
  69363. if (!scene) {
  69364. return;
  69365. }
  69366. var index = scene.multiMaterials.indexOf(this);
  69367. if (index >= 0) {
  69368. scene.multiMaterials.splice(index, 1);
  69369. }
  69370. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69371. };
  69372. return MultiMaterial;
  69373. }(BABYLON.Material));
  69374. BABYLON.MultiMaterial = MultiMaterial;
  69375. })(BABYLON || (BABYLON = {}));
  69376. //# sourceMappingURL=babylon.multiMaterial.js.map
  69377. var BABYLON;
  69378. (function (BABYLON) {
  69379. var FreeCameraTouchInput = /** @class */ (function () {
  69380. function FreeCameraTouchInput() {
  69381. this._offsetX = null;
  69382. this._offsetY = null;
  69383. this._pointerPressed = new Array();
  69384. this.touchAngularSensibility = 200000.0;
  69385. this.touchMoveSensibility = 250.0;
  69386. }
  69387. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69388. var _this = this;
  69389. var previousPosition = null;
  69390. if (this._pointerInput === undefined) {
  69391. this._onLostFocus = function (evt) {
  69392. _this._offsetX = null;
  69393. _this._offsetY = null;
  69394. };
  69395. this._pointerInput = function (p, s) {
  69396. var evt = p.event;
  69397. if (evt.pointerType === "mouse") {
  69398. return;
  69399. }
  69400. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69401. if (!noPreventDefault) {
  69402. evt.preventDefault();
  69403. }
  69404. _this._pointerPressed.push(evt.pointerId);
  69405. if (_this._pointerPressed.length !== 1) {
  69406. return;
  69407. }
  69408. previousPosition = {
  69409. x: evt.clientX,
  69410. y: evt.clientY
  69411. };
  69412. }
  69413. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69414. if (!noPreventDefault) {
  69415. evt.preventDefault();
  69416. }
  69417. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69418. if (index === -1) {
  69419. return;
  69420. }
  69421. _this._pointerPressed.splice(index, 1);
  69422. if (index != 0) {
  69423. return;
  69424. }
  69425. previousPosition = null;
  69426. _this._offsetX = null;
  69427. _this._offsetY = null;
  69428. }
  69429. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69430. if (!noPreventDefault) {
  69431. evt.preventDefault();
  69432. }
  69433. if (!previousPosition) {
  69434. return;
  69435. }
  69436. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69437. if (index != 0) {
  69438. return;
  69439. }
  69440. _this._offsetX = evt.clientX - previousPosition.x;
  69441. _this._offsetY = -(evt.clientY - previousPosition.y);
  69442. }
  69443. };
  69444. }
  69445. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69446. if (this._onLostFocus) {
  69447. element.addEventListener("blur", this._onLostFocus);
  69448. }
  69449. };
  69450. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69451. if (this._pointerInput && element) {
  69452. if (this._observer) {
  69453. this.camera.getScene().onPointerObservable.remove(this._observer);
  69454. this._observer = null;
  69455. }
  69456. if (this._onLostFocus) {
  69457. element.removeEventListener("blur", this._onLostFocus);
  69458. this._onLostFocus = null;
  69459. }
  69460. this._pointerPressed = [];
  69461. this._offsetX = null;
  69462. this._offsetY = null;
  69463. }
  69464. };
  69465. FreeCameraTouchInput.prototype.checkInputs = function () {
  69466. if (this._offsetX && this._offsetY) {
  69467. var camera = this.camera;
  69468. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69469. if (this._pointerPressed.length > 1) {
  69470. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69471. }
  69472. else {
  69473. var speed = camera._computeLocalCameraSpeed();
  69474. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69475. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69476. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69477. }
  69478. }
  69479. };
  69480. FreeCameraTouchInput.prototype.getClassName = function () {
  69481. return "FreeCameraTouchInput";
  69482. };
  69483. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69484. return "touch";
  69485. };
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69489. __decorate([
  69490. BABYLON.serialize()
  69491. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69492. return FreeCameraTouchInput;
  69493. }());
  69494. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69495. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69496. })(BABYLON || (BABYLON = {}));
  69497. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69498. var BABYLON;
  69499. (function (BABYLON) {
  69500. // We're mainly based on the logic defined into the FreeCamera code
  69501. var TouchCamera = /** @class */ (function (_super) {
  69502. __extends(TouchCamera, _super);
  69503. //-- end properties for backward compatibility for inputs
  69504. function TouchCamera(name, position, scene) {
  69505. var _this = _super.call(this, name, position, scene) || this;
  69506. _this.inputs.addTouch();
  69507. _this._setupInputs();
  69508. return _this;
  69509. }
  69510. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69511. //-- Begin properties for backward compatibility for inputs
  69512. get: function () {
  69513. var touch = this.inputs.attached["touch"];
  69514. if (touch)
  69515. return touch.touchAngularSensibility;
  69516. return 0;
  69517. },
  69518. set: function (value) {
  69519. var touch = this.inputs.attached["touch"];
  69520. if (touch)
  69521. touch.touchAngularSensibility = value;
  69522. },
  69523. enumerable: true,
  69524. configurable: true
  69525. });
  69526. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69527. get: function () {
  69528. var touch = this.inputs.attached["touch"];
  69529. if (touch)
  69530. return touch.touchMoveSensibility;
  69531. return 0;
  69532. },
  69533. set: function (value) {
  69534. var touch = this.inputs.attached["touch"];
  69535. if (touch)
  69536. touch.touchMoveSensibility = value;
  69537. },
  69538. enumerable: true,
  69539. configurable: true
  69540. });
  69541. TouchCamera.prototype.getClassName = function () {
  69542. return "TouchCamera";
  69543. };
  69544. TouchCamera.prototype._setupInputs = function () {
  69545. var mouse = this.inputs.attached["mouse"];
  69546. if (mouse) {
  69547. mouse.touchEnabled = false;
  69548. }
  69549. };
  69550. return TouchCamera;
  69551. }(BABYLON.FreeCamera));
  69552. BABYLON.TouchCamera = TouchCamera;
  69553. })(BABYLON || (BABYLON = {}));
  69554. //# sourceMappingURL=babylon.touchCamera.js.map
  69555. var BABYLON;
  69556. (function (BABYLON) {
  69557. var ProceduralTexture = /** @class */ (function (_super) {
  69558. __extends(ProceduralTexture, _super);
  69559. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69560. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69561. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69562. if (isCube === void 0) { isCube = false; }
  69563. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69564. _this.isCube = isCube;
  69565. _this.isEnabled = true;
  69566. _this._currentRefreshId = -1;
  69567. _this._refreshRate = 1;
  69568. _this._vertexBuffers = {};
  69569. _this._uniforms = new Array();
  69570. _this._samplers = new Array();
  69571. _this._textures = {};
  69572. _this._floats = {};
  69573. _this._floatsArrays = {};
  69574. _this._colors3 = {};
  69575. _this._colors4 = {};
  69576. _this._vectors2 = {};
  69577. _this._vectors3 = {};
  69578. _this._matrices = {};
  69579. _this._fallbackTextureUsed = false;
  69580. scene.proceduralTextures.push(_this);
  69581. _this._engine = scene.getEngine();
  69582. _this.name = name;
  69583. _this.isRenderTarget = true;
  69584. _this._size = size;
  69585. _this._generateMipMaps = generateMipMaps;
  69586. _this.setFragment(fragment);
  69587. _this._fallbackTexture = fallbackTexture;
  69588. if (isCube) {
  69589. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69590. _this.setFloat("face", 0);
  69591. }
  69592. else {
  69593. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69594. }
  69595. // VBO
  69596. var vertices = [];
  69597. vertices.push(1, 1);
  69598. vertices.push(-1, 1);
  69599. vertices.push(-1, -1);
  69600. vertices.push(1, -1);
  69601. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69602. _this._createIndexBuffer();
  69603. return _this;
  69604. }
  69605. ProceduralTexture.prototype._createIndexBuffer = function () {
  69606. var engine = this._engine;
  69607. // Indices
  69608. var indices = [];
  69609. indices.push(0);
  69610. indices.push(1);
  69611. indices.push(2);
  69612. indices.push(0);
  69613. indices.push(2);
  69614. indices.push(3);
  69615. this._indexBuffer = engine.createIndexBuffer(indices);
  69616. };
  69617. ProceduralTexture.prototype._rebuild = function () {
  69618. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69619. if (vb) {
  69620. vb._rebuild();
  69621. }
  69622. this._createIndexBuffer();
  69623. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69624. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69625. }
  69626. };
  69627. ProceduralTexture.prototype.reset = function () {
  69628. if (this._effect === undefined) {
  69629. return;
  69630. }
  69631. var engine = this._engine;
  69632. engine._releaseEffect(this._effect);
  69633. };
  69634. ProceduralTexture.prototype.isReady = function () {
  69635. var _this = this;
  69636. var engine = this._engine;
  69637. var shaders;
  69638. if (!this._fragment) {
  69639. return false;
  69640. }
  69641. if (this._fallbackTextureUsed) {
  69642. return true;
  69643. }
  69644. if (this._fragment.fragmentElement !== undefined) {
  69645. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69646. }
  69647. else {
  69648. shaders = { vertex: "procedural", fragment: this._fragment };
  69649. }
  69650. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69651. _this.releaseInternalTexture();
  69652. if (_this._fallbackTexture) {
  69653. _this._texture = _this._fallbackTexture._texture;
  69654. if (_this._texture) {
  69655. _this._texture.incrementReferences();
  69656. }
  69657. }
  69658. _this._fallbackTextureUsed = true;
  69659. });
  69660. return this._effect.isReady();
  69661. };
  69662. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69663. this._currentRefreshId = -1;
  69664. };
  69665. ProceduralTexture.prototype.setFragment = function (fragment) {
  69666. this._fragment = fragment;
  69667. };
  69668. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69669. get: function () {
  69670. return this._refreshRate;
  69671. },
  69672. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69673. set: function (value) {
  69674. this._refreshRate = value;
  69675. this.resetRefreshCounter();
  69676. },
  69677. enumerable: true,
  69678. configurable: true
  69679. });
  69680. ProceduralTexture.prototype._shouldRender = function () {
  69681. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69682. return false;
  69683. }
  69684. if (this._fallbackTextureUsed) {
  69685. return false;
  69686. }
  69687. if (this._currentRefreshId === -1) { // At least render once
  69688. this._currentRefreshId = 1;
  69689. return true;
  69690. }
  69691. if (this.refreshRate === this._currentRefreshId) {
  69692. this._currentRefreshId = 1;
  69693. return true;
  69694. }
  69695. this._currentRefreshId++;
  69696. return false;
  69697. };
  69698. ProceduralTexture.prototype.getRenderSize = function () {
  69699. return this._size;
  69700. };
  69701. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69702. if (this._fallbackTextureUsed) {
  69703. return;
  69704. }
  69705. this.releaseInternalTexture();
  69706. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69707. };
  69708. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69709. if (this._uniforms.indexOf(uniformName) === -1) {
  69710. this._uniforms.push(uniformName);
  69711. }
  69712. };
  69713. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69714. if (this._samplers.indexOf(name) === -1) {
  69715. this._samplers.push(name);
  69716. }
  69717. this._textures[name] = texture;
  69718. return this;
  69719. };
  69720. ProceduralTexture.prototype.setFloat = function (name, value) {
  69721. this._checkUniform(name);
  69722. this._floats[name] = value;
  69723. return this;
  69724. };
  69725. ProceduralTexture.prototype.setFloats = function (name, value) {
  69726. this._checkUniform(name);
  69727. this._floatsArrays[name] = value;
  69728. return this;
  69729. };
  69730. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69731. this._checkUniform(name);
  69732. this._colors3[name] = value;
  69733. return this;
  69734. };
  69735. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69736. this._checkUniform(name);
  69737. this._colors4[name] = value;
  69738. return this;
  69739. };
  69740. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69741. this._checkUniform(name);
  69742. this._vectors2[name] = value;
  69743. return this;
  69744. };
  69745. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69746. this._checkUniform(name);
  69747. this._vectors3[name] = value;
  69748. return this;
  69749. };
  69750. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69751. this._checkUniform(name);
  69752. this._matrices[name] = value;
  69753. return this;
  69754. };
  69755. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69756. var scene = this.getScene();
  69757. if (!scene) {
  69758. return;
  69759. }
  69760. var engine = this._engine;
  69761. // Render
  69762. engine.enableEffect(this._effect);
  69763. engine.setState(false);
  69764. // Texture
  69765. for (var name in this._textures) {
  69766. this._effect.setTexture(name, this._textures[name]);
  69767. }
  69768. // Float
  69769. for (name in this._floats) {
  69770. this._effect.setFloat(name, this._floats[name]);
  69771. }
  69772. // Floats
  69773. for (name in this._floatsArrays) {
  69774. this._effect.setArray(name, this._floatsArrays[name]);
  69775. }
  69776. // Color3
  69777. for (name in this._colors3) {
  69778. this._effect.setColor3(name, this._colors3[name]);
  69779. }
  69780. // Color4
  69781. for (name in this._colors4) {
  69782. var color = this._colors4[name];
  69783. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69784. }
  69785. // Vector2
  69786. for (name in this._vectors2) {
  69787. this._effect.setVector2(name, this._vectors2[name]);
  69788. }
  69789. // Vector3
  69790. for (name in this._vectors3) {
  69791. this._effect.setVector3(name, this._vectors3[name]);
  69792. }
  69793. // Matrix
  69794. for (name in this._matrices) {
  69795. this._effect.setMatrix(name, this._matrices[name]);
  69796. }
  69797. if (!this._texture) {
  69798. return;
  69799. }
  69800. if (this.isCube) {
  69801. for (var face = 0; face < 6; face++) {
  69802. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69803. // VBOs
  69804. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69805. this._effect.setFloat("face", face);
  69806. // Clear
  69807. engine.clear(scene.clearColor, true, true, true);
  69808. // Draw order
  69809. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69810. // Mipmaps
  69811. if (face === 5) {
  69812. engine.generateMipMapsForCubemap(this._texture);
  69813. }
  69814. }
  69815. }
  69816. else {
  69817. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69818. // VBOs
  69819. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69820. // Clear
  69821. engine.clear(scene.clearColor, true, true, true);
  69822. // Draw order
  69823. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69824. }
  69825. // Unbind
  69826. engine.unBindFramebuffer(this._texture, this.isCube);
  69827. if (this.onGenerated) {
  69828. this.onGenerated();
  69829. }
  69830. };
  69831. ProceduralTexture.prototype.clone = function () {
  69832. var textureSize = this.getSize();
  69833. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69834. // Base texture
  69835. newTexture.hasAlpha = this.hasAlpha;
  69836. newTexture.level = this.level;
  69837. // RenderTarget Texture
  69838. newTexture.coordinatesMode = this.coordinatesMode;
  69839. return newTexture;
  69840. };
  69841. ProceduralTexture.prototype.dispose = function () {
  69842. var scene = this.getScene();
  69843. if (!scene) {
  69844. return;
  69845. }
  69846. var index = scene.proceduralTextures.indexOf(this);
  69847. if (index >= 0) {
  69848. scene.proceduralTextures.splice(index, 1);
  69849. }
  69850. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69851. if (vertexBuffer) {
  69852. vertexBuffer.dispose();
  69853. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69854. }
  69855. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69856. this._indexBuffer = null;
  69857. }
  69858. _super.prototype.dispose.call(this);
  69859. };
  69860. return ProceduralTexture;
  69861. }(BABYLON.Texture));
  69862. BABYLON.ProceduralTexture = ProceduralTexture;
  69863. })(BABYLON || (BABYLON = {}));
  69864. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69865. var BABYLON;
  69866. (function (BABYLON) {
  69867. var CustomProceduralTexture = /** @class */ (function (_super) {
  69868. __extends(CustomProceduralTexture, _super);
  69869. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69870. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69871. _this._animate = true;
  69872. _this._time = 0;
  69873. _this._texturePath = texturePath;
  69874. //Try to load json
  69875. _this.loadJson(texturePath);
  69876. _this.refreshRate = 1;
  69877. return _this;
  69878. }
  69879. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69880. var _this = this;
  69881. var noConfigFile = function () {
  69882. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69883. try {
  69884. _this.setFragment(_this._texturePath);
  69885. }
  69886. catch (ex) {
  69887. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69888. }
  69889. };
  69890. var configFileUrl = jsonUrl + "/config.json";
  69891. var xhr = new XMLHttpRequest();
  69892. xhr.open("GET", configFileUrl, true);
  69893. xhr.addEventListener("load", function () {
  69894. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69895. try {
  69896. _this._config = JSON.parse(xhr.response);
  69897. _this.updateShaderUniforms();
  69898. _this.updateTextures();
  69899. _this.setFragment(_this._texturePath + "/custom");
  69900. _this._animate = _this._config.animate;
  69901. _this.refreshRate = _this._config.refreshrate;
  69902. }
  69903. catch (ex) {
  69904. noConfigFile();
  69905. }
  69906. }
  69907. else {
  69908. noConfigFile();
  69909. }
  69910. }, false);
  69911. xhr.addEventListener("error", function () {
  69912. noConfigFile();
  69913. }, false);
  69914. try {
  69915. xhr.send();
  69916. }
  69917. catch (ex) {
  69918. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69919. }
  69920. };
  69921. CustomProceduralTexture.prototype.isReady = function () {
  69922. if (!_super.prototype.isReady.call(this)) {
  69923. return false;
  69924. }
  69925. for (var name in this._textures) {
  69926. var texture = this._textures[name];
  69927. if (!texture.isReady()) {
  69928. return false;
  69929. }
  69930. }
  69931. return true;
  69932. };
  69933. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69934. var scene = this.getScene();
  69935. if (this._animate && scene) {
  69936. this._time += scene.getAnimationRatio() * 0.03;
  69937. this.updateShaderUniforms();
  69938. }
  69939. _super.prototype.render.call(this, useCameraPostProcess);
  69940. };
  69941. CustomProceduralTexture.prototype.updateTextures = function () {
  69942. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69943. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69944. }
  69945. };
  69946. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69947. if (this._config) {
  69948. for (var j = 0; j < this._config.uniforms.length; j++) {
  69949. var uniform = this._config.uniforms[j];
  69950. switch (uniform.type) {
  69951. case "float":
  69952. this.setFloat(uniform.name, uniform.value);
  69953. break;
  69954. case "color3":
  69955. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69956. break;
  69957. case "color4":
  69958. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69959. break;
  69960. case "vector2":
  69961. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69962. break;
  69963. case "vector3":
  69964. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69965. break;
  69966. }
  69967. }
  69968. }
  69969. this.setFloat("time", this._time);
  69970. };
  69971. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69972. get: function () {
  69973. return this._animate;
  69974. },
  69975. set: function (value) {
  69976. this._animate = value;
  69977. },
  69978. enumerable: true,
  69979. configurable: true
  69980. });
  69981. return CustomProceduralTexture;
  69982. }(BABYLON.ProceduralTexture));
  69983. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69984. })(BABYLON || (BABYLON = {}));
  69985. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69986. var BABYLON;
  69987. (function (BABYLON) {
  69988. var FreeCameraGamepadInput = /** @class */ (function () {
  69989. function FreeCameraGamepadInput() {
  69990. this.gamepadAngularSensibility = 200;
  69991. this.gamepadMoveSensibility = 40;
  69992. // private members
  69993. this._cameraTransform = BABYLON.Matrix.Identity();
  69994. this._deltaTransform = BABYLON.Vector3.Zero();
  69995. this._vector3 = BABYLON.Vector3.Zero();
  69996. this._vector2 = BABYLON.Vector2.Zero();
  69997. }
  69998. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69999. var _this = this;
  70000. var manager = this.camera.getScene().gamepadManager;
  70001. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70002. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70003. // prioritize XBOX gamepads.
  70004. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70005. _this.gamepad = gamepad;
  70006. }
  70007. }
  70008. });
  70009. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70010. if (_this.gamepad === gamepad) {
  70011. _this.gamepad = null;
  70012. }
  70013. });
  70014. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70015. };
  70016. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70017. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70018. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70019. this.gamepad = null;
  70020. };
  70021. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70022. if (this.gamepad && this.gamepad.leftStick) {
  70023. var camera = this.camera;
  70024. var LSValues = this.gamepad.leftStick;
  70025. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70026. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70027. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70028. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70029. var RSValues = this.gamepad.rightStick;
  70030. if (RSValues) {
  70031. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70032. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70033. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70034. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70035. }
  70036. else {
  70037. RSValues = { x: 0, y: 0 };
  70038. }
  70039. if (!camera.rotationQuaternion) {
  70040. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70041. }
  70042. else {
  70043. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70044. }
  70045. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70046. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70047. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70048. camera.cameraDirection.addInPlace(this._deltaTransform);
  70049. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70050. camera.cameraRotation.addInPlace(this._vector2);
  70051. }
  70052. };
  70053. FreeCameraGamepadInput.prototype.getClassName = function () {
  70054. return "FreeCameraGamepadInput";
  70055. };
  70056. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70057. return "gamepad";
  70058. };
  70059. __decorate([
  70060. BABYLON.serialize()
  70061. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70062. __decorate([
  70063. BABYLON.serialize()
  70064. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70065. return FreeCameraGamepadInput;
  70066. }());
  70067. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70068. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70069. })(BABYLON || (BABYLON = {}));
  70070. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70071. var BABYLON;
  70072. (function (BABYLON) {
  70073. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70074. function ArcRotateCameraGamepadInput() {
  70075. this.gamepadRotationSensibility = 80;
  70076. this.gamepadMoveSensibility = 40;
  70077. }
  70078. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70079. var _this = this;
  70080. var manager = this.camera.getScene().gamepadManager;
  70081. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70082. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70083. // prioritize XBOX gamepads.
  70084. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70085. _this.gamepad = gamepad;
  70086. }
  70087. }
  70088. });
  70089. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70090. if (_this.gamepad === gamepad) {
  70091. _this.gamepad = null;
  70092. }
  70093. });
  70094. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70095. };
  70096. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70097. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70098. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70099. this.gamepad = null;
  70100. };
  70101. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70102. if (this.gamepad) {
  70103. var camera = this.camera;
  70104. var RSValues = this.gamepad.rightStick;
  70105. if (RSValues) {
  70106. if (RSValues.x != 0) {
  70107. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70108. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70109. camera.inertialAlphaOffset += normalizedRX;
  70110. }
  70111. }
  70112. if (RSValues.y != 0) {
  70113. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70114. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70115. camera.inertialBetaOffset += normalizedRY;
  70116. }
  70117. }
  70118. }
  70119. var LSValues = this.gamepad.leftStick;
  70120. if (LSValues && LSValues.y != 0) {
  70121. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70122. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70123. this.camera.inertialRadiusOffset -= normalizedLY;
  70124. }
  70125. }
  70126. }
  70127. };
  70128. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70129. return "ArcRotateCameraGamepadInput";
  70130. };
  70131. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70132. return "gamepad";
  70133. };
  70134. __decorate([
  70135. BABYLON.serialize()
  70136. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70137. __decorate([
  70138. BABYLON.serialize()
  70139. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70140. return ArcRotateCameraGamepadInput;
  70141. }());
  70142. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70143. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70144. })(BABYLON || (BABYLON = {}));
  70145. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70146. var BABYLON;
  70147. (function (BABYLON) {
  70148. var GamepadManager = /** @class */ (function () {
  70149. function GamepadManager(_scene) {
  70150. var _this = this;
  70151. this._scene = _scene;
  70152. this._babylonGamepads = [];
  70153. this._oneGamepadConnected = false;
  70154. this._isMonitoring = false;
  70155. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70156. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70157. this._gamepadEventSupported = false;
  70158. }
  70159. else {
  70160. this._gamepadEventSupported = 'GamepadEvent' in window;
  70161. this._gamepadSupport = (navigator.getGamepads ||
  70162. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70163. }
  70164. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70165. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70166. for (var i in _this._babylonGamepads) {
  70167. var gamepad = _this._babylonGamepads[i];
  70168. if (gamepad && gamepad._isConnected) {
  70169. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70170. }
  70171. }
  70172. });
  70173. this._onGamepadConnectedEvent = function (evt) {
  70174. var gamepad = evt.gamepad;
  70175. if (gamepad.index in _this._babylonGamepads) {
  70176. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70177. return;
  70178. }
  70179. }
  70180. var newGamepad;
  70181. if (_this._babylonGamepads[gamepad.index]) {
  70182. newGamepad = _this._babylonGamepads[gamepad.index];
  70183. newGamepad.browserGamepad = gamepad;
  70184. newGamepad._isConnected = true;
  70185. }
  70186. else {
  70187. newGamepad = _this._addNewGamepad(gamepad);
  70188. }
  70189. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70190. _this._startMonitoringGamepads();
  70191. };
  70192. this._onGamepadDisconnectedEvent = function (evt) {
  70193. var gamepad = evt.gamepad;
  70194. // Remove the gamepad from the list of gamepads to monitor.
  70195. for (var i in _this._babylonGamepads) {
  70196. if (_this._babylonGamepads[i].index === gamepad.index) {
  70197. var disconnectedGamepad = _this._babylonGamepads[i];
  70198. disconnectedGamepad._isConnected = false;
  70199. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70200. break;
  70201. }
  70202. }
  70203. };
  70204. if (this._gamepadSupport) {
  70205. //first add already-connected gamepads
  70206. this._updateGamepadObjects();
  70207. if (this._babylonGamepads.length) {
  70208. this._startMonitoringGamepads();
  70209. }
  70210. // Checking if the gamepad connected event is supported (like in Firefox)
  70211. if (this._gamepadEventSupported) {
  70212. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70213. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70214. }
  70215. else {
  70216. this._startMonitoringGamepads();
  70217. }
  70218. }
  70219. }
  70220. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70221. get: function () {
  70222. return this._babylonGamepads;
  70223. },
  70224. enumerable: true,
  70225. configurable: true
  70226. });
  70227. GamepadManager.prototype.getGamepadByType = function (type) {
  70228. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70229. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70230. var gamepad = _a[_i];
  70231. if (gamepad && gamepad.type === type) {
  70232. return gamepad;
  70233. }
  70234. }
  70235. return null;
  70236. };
  70237. GamepadManager.prototype.dispose = function () {
  70238. if (this._gamepadEventSupported) {
  70239. if (this._onGamepadConnectedEvent) {
  70240. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70241. }
  70242. if (this._onGamepadDisconnectedEvent) {
  70243. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70244. }
  70245. this._onGamepadConnectedEvent = null;
  70246. this._onGamepadDisconnectedEvent = null;
  70247. }
  70248. this._babylonGamepads.forEach(function (gamepad) {
  70249. gamepad.dispose();
  70250. });
  70251. this.onGamepadConnectedObservable.clear();
  70252. this.onGamepadDisconnectedObservable.clear();
  70253. this._oneGamepadConnected = false;
  70254. this._stopMonitoringGamepads();
  70255. this._babylonGamepads = [];
  70256. };
  70257. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70258. if (!this._oneGamepadConnected) {
  70259. this._oneGamepadConnected = true;
  70260. }
  70261. var newGamepad;
  70262. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70263. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70264. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70265. }
  70266. // if pose is supported, use the (WebVR) pose enabled controller
  70267. else if (gamepad.pose) {
  70268. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70269. }
  70270. else {
  70271. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70272. }
  70273. this._babylonGamepads[newGamepad.index] = newGamepad;
  70274. return newGamepad;
  70275. };
  70276. GamepadManager.prototype._startMonitoringGamepads = function () {
  70277. if (!this._isMonitoring) {
  70278. this._isMonitoring = true;
  70279. //back-comp
  70280. if (!this._scene) {
  70281. this._checkGamepadsStatus();
  70282. }
  70283. }
  70284. };
  70285. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70286. this._isMonitoring = false;
  70287. };
  70288. GamepadManager.prototype._checkGamepadsStatus = function () {
  70289. var _this = this;
  70290. // Hack to be compatible Chrome
  70291. this._updateGamepadObjects();
  70292. for (var i in this._babylonGamepads) {
  70293. var gamepad = this._babylonGamepads[i];
  70294. if (!gamepad || !gamepad.isConnected) {
  70295. continue;
  70296. }
  70297. gamepad.update();
  70298. }
  70299. if (this._isMonitoring && !this._scene) {
  70300. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70301. }
  70302. };
  70303. // This function is called only on Chrome, which does not properly support
  70304. // connection/disconnection events and forces you to recopy again the gamepad object
  70305. GamepadManager.prototype._updateGamepadObjects = function () {
  70306. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70307. for (var i = 0; i < gamepads.length; i++) {
  70308. var gamepad = gamepads[i];
  70309. if (gamepad) {
  70310. if (!this._babylonGamepads[gamepad.index]) {
  70311. var newGamepad = this._addNewGamepad(gamepad);
  70312. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70313. }
  70314. else {
  70315. // Forced to copy again this object for Chrome for unknown reason
  70316. this._babylonGamepads[i].browserGamepad = gamepad;
  70317. if (!this._babylonGamepads[i].isConnected) {
  70318. this._babylonGamepads[i]._isConnected = true;
  70319. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70320. }
  70321. }
  70322. }
  70323. }
  70324. };
  70325. return GamepadManager;
  70326. }());
  70327. BABYLON.GamepadManager = GamepadManager;
  70328. })(BABYLON || (BABYLON = {}));
  70329. //# sourceMappingURL=babylon.gamepadManager.js.map
  70330. var BABYLON;
  70331. (function (BABYLON) {
  70332. var StickValues = /** @class */ (function () {
  70333. function StickValues(x, y) {
  70334. this.x = x;
  70335. this.y = y;
  70336. }
  70337. return StickValues;
  70338. }());
  70339. BABYLON.StickValues = StickValues;
  70340. var Gamepad = /** @class */ (function () {
  70341. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70342. if (leftStickX === void 0) { leftStickX = 0; }
  70343. if (leftStickY === void 0) { leftStickY = 1; }
  70344. if (rightStickX === void 0) { rightStickX = 2; }
  70345. if (rightStickY === void 0) { rightStickY = 3; }
  70346. this.id = id;
  70347. this.index = index;
  70348. this.browserGamepad = browserGamepad;
  70349. this._isConnected = true;
  70350. this._invertLeftStickY = false;
  70351. this.type = Gamepad.GAMEPAD;
  70352. this._leftStickAxisX = leftStickX;
  70353. this._leftStickAxisY = leftStickY;
  70354. this._rightStickAxisX = rightStickX;
  70355. this._rightStickAxisY = rightStickY;
  70356. if (this.browserGamepad.axes.length >= 2) {
  70357. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70358. }
  70359. if (this.browserGamepad.axes.length >= 4) {
  70360. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70361. }
  70362. }
  70363. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70364. get: function () {
  70365. return this._isConnected;
  70366. },
  70367. enumerable: true,
  70368. configurable: true
  70369. });
  70370. Gamepad.prototype.onleftstickchanged = function (callback) {
  70371. this._onleftstickchanged = callback;
  70372. };
  70373. Gamepad.prototype.onrightstickchanged = function (callback) {
  70374. this._onrightstickchanged = callback;
  70375. };
  70376. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70377. get: function () {
  70378. return this._leftStick;
  70379. },
  70380. set: function (newValues) {
  70381. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70382. this._onleftstickchanged(newValues);
  70383. }
  70384. this._leftStick = newValues;
  70385. },
  70386. enumerable: true,
  70387. configurable: true
  70388. });
  70389. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70390. get: function () {
  70391. return this._rightStick;
  70392. },
  70393. set: function (newValues) {
  70394. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70395. this._onrightstickchanged(newValues);
  70396. }
  70397. this._rightStick = newValues;
  70398. },
  70399. enumerable: true,
  70400. configurable: true
  70401. });
  70402. Gamepad.prototype.update = function () {
  70403. if (this._leftStick) {
  70404. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70405. if (this._invertLeftStickY) {
  70406. this.leftStick.y *= -1;
  70407. }
  70408. }
  70409. if (this._rightStick) {
  70410. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70411. }
  70412. };
  70413. Gamepad.prototype.dispose = function () {
  70414. };
  70415. Gamepad.GAMEPAD = 0;
  70416. Gamepad.GENERIC = 1;
  70417. Gamepad.XBOX = 2;
  70418. Gamepad.POSE_ENABLED = 3;
  70419. return Gamepad;
  70420. }());
  70421. BABYLON.Gamepad = Gamepad;
  70422. var GenericPad = /** @class */ (function (_super) {
  70423. __extends(GenericPad, _super);
  70424. function GenericPad(id, index, browserGamepad) {
  70425. var _this = _super.call(this, id, index, browserGamepad) || this;
  70426. _this.onButtonDownObservable = new BABYLON.Observable();
  70427. _this.onButtonUpObservable = new BABYLON.Observable();
  70428. _this.type = Gamepad.GENERIC;
  70429. _this._buttons = new Array(browserGamepad.buttons.length);
  70430. return _this;
  70431. }
  70432. GenericPad.prototype.onbuttondown = function (callback) {
  70433. this._onbuttondown = callback;
  70434. };
  70435. GenericPad.prototype.onbuttonup = function (callback) {
  70436. this._onbuttonup = callback;
  70437. };
  70438. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70439. if (newValue !== currentValue) {
  70440. if (newValue === 1) {
  70441. if (this._onbuttondown) {
  70442. this._onbuttondown(buttonIndex);
  70443. }
  70444. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70445. }
  70446. if (newValue === 0) {
  70447. if (this._onbuttonup) {
  70448. this._onbuttonup(buttonIndex);
  70449. }
  70450. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70451. }
  70452. }
  70453. return newValue;
  70454. };
  70455. GenericPad.prototype.update = function () {
  70456. _super.prototype.update.call(this);
  70457. for (var index = 0; index < this._buttons.length; index++) {
  70458. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70459. }
  70460. };
  70461. GenericPad.prototype.dispose = function () {
  70462. _super.prototype.dispose.call(this);
  70463. this.onButtonDownObservable.clear();
  70464. this.onButtonUpObservable.clear();
  70465. };
  70466. return GenericPad;
  70467. }(Gamepad));
  70468. BABYLON.GenericPad = GenericPad;
  70469. })(BABYLON || (BABYLON = {}));
  70470. //# sourceMappingURL=babylon.gamepad.js.map
  70471. var BABYLON;
  70472. (function (BABYLON) {
  70473. /**
  70474. * Defines supported buttons for XBox360 compatible gamepads
  70475. */
  70476. var Xbox360Button;
  70477. (function (Xbox360Button) {
  70478. /** A */
  70479. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70480. /** B */
  70481. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70482. /** X */
  70483. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70484. /** Y */
  70485. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70486. /** Start */
  70487. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70488. /** Back */
  70489. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70490. /** Left button */
  70491. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70492. /** Right button */
  70493. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70494. /** Left stick */
  70495. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70496. /** Right stick */
  70497. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70498. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70499. /** Defines values for XBox360 DPad */
  70500. var Xbox360Dpad;
  70501. (function (Xbox360Dpad) {
  70502. /** Up */
  70503. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70504. /** Down */
  70505. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70506. /** Left */
  70507. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70508. /** Right */
  70509. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70510. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70511. /**
  70512. * Defines a XBox360 gamepad
  70513. */
  70514. var Xbox360Pad = /** @class */ (function (_super) {
  70515. __extends(Xbox360Pad, _super);
  70516. /**
  70517. * Creates a new XBox360 gamepad object
  70518. * @param id defines the id of this gamepad
  70519. * @param index defines its index
  70520. * @param gamepad defines the internal HTML gamepad object
  70521. * @param xboxOne defines if it is a XBox One gamepad
  70522. */
  70523. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70524. if (xboxOne === void 0) { xboxOne = false; }
  70525. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70526. _this._leftTrigger = 0;
  70527. _this._rightTrigger = 0;
  70528. /** Observable raised when a button is pressed */
  70529. _this.onButtonDownObservable = new BABYLON.Observable();
  70530. /** Observable raised when a button is released */
  70531. _this.onButtonUpObservable = new BABYLON.Observable();
  70532. /** Observable raised when a pad is pressed */
  70533. _this.onPadDownObservable = new BABYLON.Observable();
  70534. /** Observable raised when a pad is released */
  70535. _this.onPadUpObservable = new BABYLON.Observable();
  70536. _this._buttonA = 0;
  70537. _this._buttonB = 0;
  70538. _this._buttonX = 0;
  70539. _this._buttonY = 0;
  70540. _this._buttonBack = 0;
  70541. _this._buttonStart = 0;
  70542. _this._buttonLB = 0;
  70543. _this._buttonRB = 0;
  70544. _this._buttonLeftStick = 0;
  70545. _this._buttonRightStick = 0;
  70546. _this._dPadUp = 0;
  70547. _this._dPadDown = 0;
  70548. _this._dPadLeft = 0;
  70549. _this._dPadRight = 0;
  70550. _this._isXboxOnePad = false;
  70551. _this.type = BABYLON.Gamepad.XBOX;
  70552. _this._isXboxOnePad = xboxOne;
  70553. return _this;
  70554. }
  70555. /**
  70556. * Defines the callback to call when left trigger is pressed
  70557. * @param callback defines the callback to use
  70558. */
  70559. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70560. this._onlefttriggerchanged = callback;
  70561. };
  70562. /**
  70563. * Defines the callback to call when right trigger is pressed
  70564. * @param callback defines the callback to use
  70565. */
  70566. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70567. this._onrighttriggerchanged = callback;
  70568. };
  70569. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70570. /**
  70571. * Gets or sets left trigger value
  70572. */
  70573. get: function () {
  70574. return this._leftTrigger;
  70575. },
  70576. set: function (newValue) {
  70577. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70578. this._onlefttriggerchanged(newValue);
  70579. }
  70580. this._leftTrigger = newValue;
  70581. },
  70582. enumerable: true,
  70583. configurable: true
  70584. });
  70585. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70586. /**
  70587. * Gets or sets right trigger value
  70588. */
  70589. get: function () {
  70590. return this._rightTrigger;
  70591. },
  70592. set: function (newValue) {
  70593. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70594. this._onrighttriggerchanged(newValue);
  70595. }
  70596. this._rightTrigger = newValue;
  70597. },
  70598. enumerable: true,
  70599. configurable: true
  70600. });
  70601. /**
  70602. * Defines the callback to call when a button is pressed
  70603. * @param callback defines the callback to use
  70604. */
  70605. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70606. this._onbuttondown = callback;
  70607. };
  70608. /**
  70609. * Defines the callback to call when a button is released
  70610. * @param callback defines the callback to use
  70611. */
  70612. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70613. this._onbuttonup = callback;
  70614. };
  70615. /**
  70616. * Defines the callback to call when a pad is pressed
  70617. * @param callback defines the callback to use
  70618. */
  70619. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70620. this._ondpaddown = callback;
  70621. };
  70622. /**
  70623. * Defines the callback to call when a pad is released
  70624. * @param callback defines the callback to use
  70625. */
  70626. Xbox360Pad.prototype.ondpadup = function (callback) {
  70627. this._ondpadup = callback;
  70628. };
  70629. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70630. if (newValue !== currentValue) {
  70631. if (newValue === 1) {
  70632. if (this._onbuttondown) {
  70633. this._onbuttondown(buttonType);
  70634. }
  70635. this.onButtonDownObservable.notifyObservers(buttonType);
  70636. }
  70637. if (newValue === 0) {
  70638. if (this._onbuttonup) {
  70639. this._onbuttonup(buttonType);
  70640. }
  70641. this.onButtonUpObservable.notifyObservers(buttonType);
  70642. }
  70643. }
  70644. return newValue;
  70645. };
  70646. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70647. if (newValue !== currentValue) {
  70648. if (newValue === 1) {
  70649. if (this._ondpaddown) {
  70650. this._ondpaddown(buttonType);
  70651. }
  70652. this.onPadDownObservable.notifyObservers(buttonType);
  70653. }
  70654. if (newValue === 0) {
  70655. if (this._ondpadup) {
  70656. this._ondpadup(buttonType);
  70657. }
  70658. this.onPadUpObservable.notifyObservers(buttonType);
  70659. }
  70660. }
  70661. return newValue;
  70662. };
  70663. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70664. /** Gets or sets value of A button */
  70665. get: function () {
  70666. return this._buttonA;
  70667. },
  70668. set: function (value) {
  70669. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70670. },
  70671. enumerable: true,
  70672. configurable: true
  70673. });
  70674. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70675. /** Gets or sets value of B button */
  70676. get: function () {
  70677. return this._buttonB;
  70678. },
  70679. set: function (value) {
  70680. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70681. },
  70682. enumerable: true,
  70683. configurable: true
  70684. });
  70685. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70686. /** Gets or sets value of X button */
  70687. get: function () {
  70688. return this._buttonX;
  70689. },
  70690. set: function (value) {
  70691. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70692. },
  70693. enumerable: true,
  70694. configurable: true
  70695. });
  70696. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70697. /** Gets or sets value of Y button */
  70698. get: function () {
  70699. return this._buttonY;
  70700. },
  70701. set: function (value) {
  70702. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70703. },
  70704. enumerable: true,
  70705. configurable: true
  70706. });
  70707. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70708. /** Gets or sets value of Start button */
  70709. get: function () {
  70710. return this._buttonStart;
  70711. },
  70712. set: function (value) {
  70713. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70714. },
  70715. enumerable: true,
  70716. configurable: true
  70717. });
  70718. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70719. /** Gets or sets value of Back button */
  70720. get: function () {
  70721. return this._buttonBack;
  70722. },
  70723. set: function (value) {
  70724. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70725. },
  70726. enumerable: true,
  70727. configurable: true
  70728. });
  70729. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70730. /** Gets or sets value of Left button */
  70731. get: function () {
  70732. return this._buttonLB;
  70733. },
  70734. set: function (value) {
  70735. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70736. },
  70737. enumerable: true,
  70738. configurable: true
  70739. });
  70740. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70741. /** Gets or sets value of Right button */
  70742. get: function () {
  70743. return this._buttonRB;
  70744. },
  70745. set: function (value) {
  70746. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70747. },
  70748. enumerable: true,
  70749. configurable: true
  70750. });
  70751. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70752. /** Gets or sets value of left stick */
  70753. get: function () {
  70754. return this._buttonLeftStick;
  70755. },
  70756. set: function (value) {
  70757. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70758. },
  70759. enumerable: true,
  70760. configurable: true
  70761. });
  70762. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70763. /** Gets or sets value of right stick */
  70764. get: function () {
  70765. return this._buttonRightStick;
  70766. },
  70767. set: function (value) {
  70768. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70769. },
  70770. enumerable: true,
  70771. configurable: true
  70772. });
  70773. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70774. /** Gets or sets value of DPad up */
  70775. get: function () {
  70776. return this._dPadUp;
  70777. },
  70778. set: function (value) {
  70779. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70780. },
  70781. enumerable: true,
  70782. configurable: true
  70783. });
  70784. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70785. /** Gets or sets value of DPad down */
  70786. get: function () {
  70787. return this._dPadDown;
  70788. },
  70789. set: function (value) {
  70790. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70791. },
  70792. enumerable: true,
  70793. configurable: true
  70794. });
  70795. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70796. /** Gets or sets value of DPad left */
  70797. get: function () {
  70798. return this._dPadLeft;
  70799. },
  70800. set: function (value) {
  70801. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70807. /** Gets or sets value of DPad right */
  70808. get: function () {
  70809. return this._dPadRight;
  70810. },
  70811. set: function (value) {
  70812. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70813. },
  70814. enumerable: true,
  70815. configurable: true
  70816. });
  70817. /**
  70818. * Force the gamepad to synchronize with device values
  70819. */
  70820. Xbox360Pad.prototype.update = function () {
  70821. _super.prototype.update.call(this);
  70822. if (this._isXboxOnePad) {
  70823. this.buttonA = this.browserGamepad.buttons[0].value;
  70824. this.buttonB = this.browserGamepad.buttons[1].value;
  70825. this.buttonX = this.browserGamepad.buttons[2].value;
  70826. this.buttonY = this.browserGamepad.buttons[3].value;
  70827. this.buttonLB = this.browserGamepad.buttons[4].value;
  70828. this.buttonRB = this.browserGamepad.buttons[5].value;
  70829. this.leftTrigger = this.browserGamepad.axes[2];
  70830. this.rightTrigger = this.browserGamepad.axes[5];
  70831. this.buttonBack = this.browserGamepad.buttons[9].value;
  70832. this.buttonStart = this.browserGamepad.buttons[8].value;
  70833. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70834. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70835. this.dPadUp = this.browserGamepad.buttons[11].value;
  70836. this.dPadDown = this.browserGamepad.buttons[12].value;
  70837. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70838. this.dPadRight = this.browserGamepad.buttons[14].value;
  70839. }
  70840. else {
  70841. this.buttonA = this.browserGamepad.buttons[0].value;
  70842. this.buttonB = this.browserGamepad.buttons[1].value;
  70843. this.buttonX = this.browserGamepad.buttons[2].value;
  70844. this.buttonY = this.browserGamepad.buttons[3].value;
  70845. this.buttonLB = this.browserGamepad.buttons[4].value;
  70846. this.buttonRB = this.browserGamepad.buttons[5].value;
  70847. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70848. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70849. this.buttonBack = this.browserGamepad.buttons[8].value;
  70850. this.buttonStart = this.browserGamepad.buttons[9].value;
  70851. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70852. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70853. this.dPadUp = this.browserGamepad.buttons[12].value;
  70854. this.dPadDown = this.browserGamepad.buttons[13].value;
  70855. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70856. this.dPadRight = this.browserGamepad.buttons[15].value;
  70857. }
  70858. };
  70859. Xbox360Pad.prototype.dispose = function () {
  70860. _super.prototype.dispose.call(this);
  70861. this.onButtonDownObservable.clear();
  70862. this.onButtonUpObservable.clear();
  70863. this.onPadDownObservable.clear();
  70864. this.onPadUpObservable.clear();
  70865. };
  70866. return Xbox360Pad;
  70867. }(BABYLON.Gamepad));
  70868. BABYLON.Xbox360Pad = Xbox360Pad;
  70869. })(BABYLON || (BABYLON = {}));
  70870. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70871. var BABYLON;
  70872. (function (BABYLON) {
  70873. /**
  70874. * Defines the types of pose enabled controllers that are supported
  70875. */
  70876. var PoseEnabledControllerType;
  70877. (function (PoseEnabledControllerType) {
  70878. /**
  70879. * HTC Vive
  70880. */
  70881. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70882. /**
  70883. * Oculus Rift
  70884. */
  70885. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70886. /**
  70887. * Windows mixed reality
  70888. */
  70889. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70890. /**
  70891. * Samsung gear VR
  70892. */
  70893. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70894. /**
  70895. * Google Daydream
  70896. */
  70897. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70898. /**
  70899. * Generic
  70900. */
  70901. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70902. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70903. /**
  70904. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70905. */
  70906. var PoseEnabledControllerHelper = /** @class */ (function () {
  70907. function PoseEnabledControllerHelper() {
  70908. }
  70909. /**
  70910. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70911. * @param vrGamepad the gamepad to initialized
  70912. * @returns a vr controller of the type the gamepad identified as
  70913. */
  70914. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70915. // Oculus Touch
  70916. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70917. return new BABYLON.OculusTouchController(vrGamepad);
  70918. }
  70919. // Windows Mixed Reality controllers
  70920. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70921. return new BABYLON.WindowsMotionController(vrGamepad);
  70922. }
  70923. // HTC Vive
  70924. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70925. return new BABYLON.ViveController(vrGamepad);
  70926. }
  70927. // Samsung/Oculus Gear VR
  70928. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70929. return new BABYLON.GearVRController(vrGamepad);
  70930. }
  70931. // Google Daydream
  70932. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70933. return new BABYLON.DaydreamController(vrGamepad);
  70934. }
  70935. // Generic
  70936. else {
  70937. return new BABYLON.GenericController(vrGamepad);
  70938. }
  70939. };
  70940. return PoseEnabledControllerHelper;
  70941. }());
  70942. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70943. /**
  70944. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70945. */
  70946. var PoseEnabledController = /** @class */ (function (_super) {
  70947. __extends(PoseEnabledController, _super);
  70948. /**
  70949. * Creates a new PoseEnabledController from a gamepad
  70950. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70951. */
  70952. function PoseEnabledController(browserGamepad) {
  70953. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70954. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70955. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70956. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70957. /**
  70958. * The device position in babylon space
  70959. */
  70960. _this.devicePosition = BABYLON.Vector3.Zero();
  70961. /**
  70962. * The device rotation in babylon space
  70963. */
  70964. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70965. /**
  70966. * The scale factor of the device in babylon space
  70967. */
  70968. _this.deviceScaleFactor = 1;
  70969. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70970. /**
  70971. * Internal, matrix used to convert room space to babylon space
  70972. */
  70973. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70974. /**
  70975. * Node to be used when casting a ray from the controller
  70976. */
  70977. _this._pointingPoseNode = null;
  70978. _this._workingMatrix = BABYLON.Matrix.Identity();
  70979. /**
  70980. * @hidden
  70981. */
  70982. _this._meshAttachedObservable = new BABYLON.Observable();
  70983. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70984. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70985. _this.position = BABYLON.Vector3.Zero();
  70986. _this.rotationQuaternion = new BABYLON.Quaternion();
  70987. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70988. _this._calculatedRotation = new BABYLON.Quaternion();
  70989. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70990. return _this;
  70991. }
  70992. /**
  70993. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70994. */
  70995. PoseEnabledController.prototype.update = function () {
  70996. _super.prototype.update.call(this);
  70997. var pose = this.browserGamepad.pose;
  70998. this.updateFromDevice(pose);
  70999. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71000. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71001. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71002. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71003. if (this._mesh) {
  71004. this._mesh.position.copyFrom(this.devicePosition);
  71005. if (this._mesh.rotationQuaternion) {
  71006. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71007. }
  71008. }
  71009. };
  71010. /**
  71011. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71012. * @param poseData raw pose fromthe device
  71013. */
  71014. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71015. if (poseData) {
  71016. this.rawPose = poseData;
  71017. if (poseData.position) {
  71018. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71019. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71020. this._deviceRoomPosition.z *= -1;
  71021. }
  71022. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71023. this._calculatedPosition.addInPlace(this.position);
  71024. }
  71025. var pose = this.rawPose;
  71026. if (poseData.orientation && pose.orientation) {
  71027. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71028. if (this._mesh) {
  71029. if (this._mesh.getScene().useRightHandedSystem) {
  71030. this._deviceRoomRotationQuaternion.z *= -1;
  71031. this._deviceRoomRotationQuaternion.w *= -1;
  71032. }
  71033. else {
  71034. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71035. }
  71036. }
  71037. // if the camera is set, rotate to the camera's rotation
  71038. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71039. }
  71040. }
  71041. };
  71042. /**
  71043. * Attaches a mesh to the controller
  71044. * @param mesh the mesh to be attached
  71045. */
  71046. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71047. if (this._mesh) {
  71048. this._mesh.parent = null;
  71049. }
  71050. this._mesh = mesh;
  71051. if (this._poseControlledCamera) {
  71052. this._mesh.parent = this._poseControlledCamera;
  71053. }
  71054. if (!this._mesh.rotationQuaternion) {
  71055. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71056. }
  71057. this._meshAttachedObservable.notifyObservers(mesh);
  71058. };
  71059. /**
  71060. * Attaches the controllers mesh to a camera
  71061. * @param camera the camera the mesh should be attached to
  71062. */
  71063. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71064. this._poseControlledCamera = camera;
  71065. if (this._mesh) {
  71066. this._mesh.parent = this._poseControlledCamera;
  71067. }
  71068. };
  71069. /**
  71070. * Disposes of the controller
  71071. */
  71072. PoseEnabledController.prototype.dispose = function () {
  71073. if (this._mesh) {
  71074. this._mesh.dispose();
  71075. }
  71076. this._mesh = null;
  71077. _super.prototype.dispose.call(this);
  71078. };
  71079. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71080. /**
  71081. * The mesh that is attached to the controller
  71082. */
  71083. get: function () {
  71084. return this._mesh;
  71085. },
  71086. enumerable: true,
  71087. configurable: true
  71088. });
  71089. /**
  71090. * Gets the ray of the controller in the direction the controller is pointing
  71091. * @param length the length the resulting ray should be
  71092. * @returns a ray in the direction the controller is pointing
  71093. */
  71094. PoseEnabledController.prototype.getForwardRay = function (length) {
  71095. if (length === void 0) { length = 100; }
  71096. if (!this.mesh) {
  71097. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71098. }
  71099. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71100. var origin = m.getTranslation();
  71101. var forward = new BABYLON.Vector3(0, 0, -1);
  71102. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71103. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71104. return new BABYLON.Ray(origin, direction, length);
  71105. };
  71106. /**
  71107. * Name of the child mesh that can be used to cast a ray from the controller
  71108. */
  71109. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71110. return PoseEnabledController;
  71111. }(BABYLON.Gamepad));
  71112. BABYLON.PoseEnabledController = PoseEnabledController;
  71113. })(BABYLON || (BABYLON = {}));
  71114. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71115. var BABYLON;
  71116. (function (BABYLON) {
  71117. /**
  71118. * Defines the WebVRController object that represents controllers tracked in 3D space
  71119. */
  71120. var WebVRController = /** @class */ (function (_super) {
  71121. __extends(WebVRController, _super);
  71122. /**
  71123. * Creates a new WebVRController from a gamepad
  71124. * @param vrGamepad the gamepad that the WebVRController should be created from
  71125. */
  71126. function WebVRController(vrGamepad) {
  71127. var _this = _super.call(this, vrGamepad) || this;
  71128. // Observables
  71129. /**
  71130. * Fired when the trigger state has changed
  71131. */
  71132. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71133. /**
  71134. * Fired when the main button state has changed
  71135. */
  71136. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71137. /**
  71138. * Fired when the secondary button state has changed
  71139. */
  71140. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71141. /**
  71142. * Fired when the pad state has changed
  71143. */
  71144. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71145. /**
  71146. * Fired when controllers stick values have changed
  71147. */
  71148. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71149. /**
  71150. * X and Y axis corrisponding to the controllers joystick
  71151. */
  71152. _this.pad = { x: 0, y: 0 };
  71153. // avoid GC, store state in a tmp object
  71154. _this._changes = {
  71155. pressChanged: false,
  71156. touchChanged: false,
  71157. valueChanged: false,
  71158. changed: false
  71159. };
  71160. _this._buttons = new Array(vrGamepad.buttons.length);
  71161. _this.hand = vrGamepad.hand;
  71162. return _this;
  71163. }
  71164. /**
  71165. * Fired when a controller button's state has changed
  71166. * @param callback the callback containing the button that was modified
  71167. */
  71168. WebVRController.prototype.onButtonStateChange = function (callback) {
  71169. this._onButtonStateChange = callback;
  71170. };
  71171. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71172. /**
  71173. * The default controller model for the controller
  71174. */
  71175. get: function () {
  71176. return this._defaultModel;
  71177. },
  71178. enumerable: true,
  71179. configurable: true
  71180. });
  71181. /**
  71182. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71183. */
  71184. WebVRController.prototype.update = function () {
  71185. _super.prototype.update.call(this);
  71186. for (var index = 0; index < this._buttons.length; index++) {
  71187. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71188. }
  71189. ;
  71190. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71191. this.pad.x = this.leftStick.x;
  71192. this.pad.y = this.leftStick.y;
  71193. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71194. }
  71195. };
  71196. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71197. if (!newState) {
  71198. newState = {
  71199. pressed: false,
  71200. touched: false,
  71201. value: 0
  71202. };
  71203. }
  71204. if (!currentState) {
  71205. this._buttons[buttonIndex] = {
  71206. pressed: newState.pressed,
  71207. touched: newState.touched,
  71208. value: newState.value
  71209. };
  71210. return;
  71211. }
  71212. this._checkChanges(newState, currentState);
  71213. if (this._changes.changed) {
  71214. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71215. this._handleButtonChange(buttonIndex, newState, this._changes);
  71216. }
  71217. this._buttons[buttonIndex].pressed = newState.pressed;
  71218. this._buttons[buttonIndex].touched = newState.touched;
  71219. // oculus triggers are never 0, thou not touched.
  71220. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71221. };
  71222. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71223. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71224. this._changes.touchChanged = newState.touched !== currentState.touched;
  71225. this._changes.valueChanged = newState.value !== currentState.value;
  71226. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71227. return this._changes;
  71228. };
  71229. /**
  71230. * Disposes of th webVRCOntroller
  71231. */
  71232. WebVRController.prototype.dispose = function () {
  71233. _super.prototype.dispose.call(this);
  71234. this.onTriggerStateChangedObservable.clear();
  71235. this.onMainButtonStateChangedObservable.clear();
  71236. this.onSecondaryButtonStateChangedObservable.clear();
  71237. this.onPadStateChangedObservable.clear();
  71238. this.onPadValuesChangedObservable.clear();
  71239. };
  71240. return WebVRController;
  71241. }(BABYLON.PoseEnabledController));
  71242. BABYLON.WebVRController = WebVRController;
  71243. })(BABYLON || (BABYLON = {}));
  71244. //# sourceMappingURL=babylon.webVRController.js.map
  71245. var BABYLON;
  71246. (function (BABYLON) {
  71247. /**
  71248. * Oculus Touch Controller
  71249. */
  71250. var OculusTouchController = /** @class */ (function (_super) {
  71251. __extends(OculusTouchController, _super);
  71252. /**
  71253. * Creates a new OculusTouchController from a gamepad
  71254. * @param vrGamepad the gamepad that the controller should be created from
  71255. */
  71256. function OculusTouchController(vrGamepad) {
  71257. var _this = _super.call(this, vrGamepad) || this;
  71258. /**
  71259. * Fired when the secondary trigger on this controller is modified
  71260. */
  71261. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71262. /**
  71263. * Fired when the thumb rest on this controller is modified
  71264. */
  71265. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71266. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71267. return _this;
  71268. }
  71269. /**
  71270. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71271. * @param scene scene in which to add meshes
  71272. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71273. */
  71274. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71275. var _this = this;
  71276. var meshName;
  71277. // Hand
  71278. if (this.hand === 'left') {
  71279. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71280. }
  71281. else { // Right is the default if no hand is specified
  71282. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71283. }
  71284. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71285. /*
  71286. Parent Mesh name: oculus_touch_left
  71287. - body
  71288. - trigger
  71289. - thumbstick
  71290. - grip
  71291. - button_y
  71292. - button_x
  71293. - button_enter
  71294. */
  71295. _this._defaultModel = newMeshes[1];
  71296. _this.attachToMesh(_this._defaultModel);
  71297. if (meshLoaded) {
  71298. meshLoaded(_this._defaultModel);
  71299. }
  71300. });
  71301. };
  71302. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71303. /**
  71304. * Fired when the A button on this controller is modified
  71305. */
  71306. get: function () {
  71307. if (this.hand === 'right') {
  71308. return this.onMainButtonStateChangedObservable;
  71309. }
  71310. else {
  71311. throw new Error('No A button on left hand');
  71312. }
  71313. },
  71314. enumerable: true,
  71315. configurable: true
  71316. });
  71317. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71318. /**
  71319. * Fired when the B button on this controller is modified
  71320. */
  71321. get: function () {
  71322. if (this.hand === 'right') {
  71323. return this.onSecondaryButtonStateChangedObservable;
  71324. }
  71325. else {
  71326. throw new Error('No B button on left hand');
  71327. }
  71328. },
  71329. enumerable: true,
  71330. configurable: true
  71331. });
  71332. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71333. /**
  71334. * Fired when the X button on this controller is modified
  71335. */
  71336. get: function () {
  71337. if (this.hand === 'left') {
  71338. return this.onMainButtonStateChangedObservable;
  71339. }
  71340. else {
  71341. throw new Error('No X button on right hand');
  71342. }
  71343. },
  71344. enumerable: true,
  71345. configurable: true
  71346. });
  71347. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71348. /**
  71349. * Fired when the Y button on this controller is modified
  71350. */
  71351. get: function () {
  71352. if (this.hand === 'left') {
  71353. return this.onSecondaryButtonStateChangedObservable;
  71354. }
  71355. else {
  71356. throw new Error('No Y button on right hand');
  71357. }
  71358. },
  71359. enumerable: true,
  71360. configurable: true
  71361. });
  71362. /**
  71363. * Called once for each button that changed state since the last frame
  71364. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71365. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71366. * 2) secondary trigger (same)
  71367. * 3) A (right) X (left), touch, pressed = value
  71368. * 4) B / Y
  71369. * 5) thumb rest
  71370. * @param buttonIdx Which button index changed
  71371. * @param state New state of the button
  71372. * @param changes Which properties on the state changed since last frame
  71373. */
  71374. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71375. var notifyObject = state; //{ state: state, changes: changes };
  71376. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71377. switch (buttonIdx) {
  71378. case 0:
  71379. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71380. return;
  71381. case 1: // index trigger
  71382. if (this._defaultModel) {
  71383. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71384. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71385. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71386. }
  71387. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71388. return;
  71389. case 2: // secondary trigger
  71390. if (this._defaultModel) {
  71391. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71392. }
  71393. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71394. return;
  71395. case 3:
  71396. if (this._defaultModel) {
  71397. if (notifyObject.pressed) {
  71398. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71399. }
  71400. else {
  71401. (this._defaultModel.getChildren()[1]).position.y = 0;
  71402. }
  71403. }
  71404. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71405. return;
  71406. case 4:
  71407. if (this._defaultModel) {
  71408. if (notifyObject.pressed) {
  71409. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71410. }
  71411. else {
  71412. (this._defaultModel.getChildren()[2]).position.y = 0;
  71413. }
  71414. }
  71415. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71416. return;
  71417. case 5:
  71418. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71419. return;
  71420. }
  71421. };
  71422. /**
  71423. * Base Url for the controller model.
  71424. */
  71425. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71426. /**
  71427. * File name for the left controller model.
  71428. */
  71429. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71430. /**
  71431. * File name for the right controller model.
  71432. */
  71433. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71434. return OculusTouchController;
  71435. }(BABYLON.WebVRController));
  71436. BABYLON.OculusTouchController = OculusTouchController;
  71437. })(BABYLON || (BABYLON = {}));
  71438. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71439. var BABYLON;
  71440. (function (BABYLON) {
  71441. /**
  71442. * Vive Controller
  71443. */
  71444. var ViveController = /** @class */ (function (_super) {
  71445. __extends(ViveController, _super);
  71446. /**
  71447. * Creates a new ViveController from a gamepad
  71448. * @param vrGamepad the gamepad that the controller should be created from
  71449. */
  71450. function ViveController(vrGamepad) {
  71451. var _this = _super.call(this, vrGamepad) || this;
  71452. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71453. _this._invertLeftStickY = true;
  71454. return _this;
  71455. }
  71456. /**
  71457. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71458. * @param scene scene in which to add meshes
  71459. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71460. */
  71461. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71462. var _this = this;
  71463. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71464. /*
  71465. Parent Mesh name: ViveWand
  71466. - body
  71467. - r_gripper
  71468. - l_gripper
  71469. - menu_button
  71470. - system_button
  71471. - trackpad
  71472. - trigger
  71473. - LED
  71474. */
  71475. _this._defaultModel = newMeshes[1];
  71476. _this.attachToMesh(_this._defaultModel);
  71477. if (meshLoaded) {
  71478. meshLoaded(_this._defaultModel);
  71479. }
  71480. });
  71481. };
  71482. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71483. /**
  71484. * Fired when the left button on this controller is modified
  71485. */
  71486. get: function () {
  71487. return this.onMainButtonStateChangedObservable;
  71488. },
  71489. enumerable: true,
  71490. configurable: true
  71491. });
  71492. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71493. /**
  71494. * Fired when the right button on this controller is modified
  71495. */
  71496. get: function () {
  71497. return this.onMainButtonStateChangedObservable;
  71498. },
  71499. enumerable: true,
  71500. configurable: true
  71501. });
  71502. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71503. /**
  71504. * Fired when the menu button on this controller is modified
  71505. */
  71506. get: function () {
  71507. return this.onSecondaryButtonStateChangedObservable;
  71508. },
  71509. enumerable: true,
  71510. configurable: true
  71511. });
  71512. /**
  71513. * Called once for each button that changed state since the last frame
  71514. * Vive mapping:
  71515. * 0: touchpad
  71516. * 1: trigger
  71517. * 2: left AND right buttons
  71518. * 3: menu button
  71519. * @param buttonIdx Which button index changed
  71520. * @param state New state of the button
  71521. * @param changes Which properties on the state changed since last frame
  71522. */
  71523. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71524. var notifyObject = state; //{ state: state, changes: changes };
  71525. switch (buttonIdx) {
  71526. case 0:
  71527. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71528. return;
  71529. case 1: // index trigger
  71530. if (this._defaultModel) {
  71531. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71532. }
  71533. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71534. return;
  71535. case 2: // left AND right button
  71536. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71537. return;
  71538. case 3:
  71539. if (this._defaultModel) {
  71540. if (notifyObject.pressed) {
  71541. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71542. }
  71543. else {
  71544. (this._defaultModel.getChildren()[2]).position.y = 0;
  71545. }
  71546. }
  71547. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71548. return;
  71549. }
  71550. };
  71551. /**
  71552. * Base Url for the controller model.
  71553. */
  71554. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71555. /**
  71556. * File name for the controller model.
  71557. */
  71558. ViveController.MODEL_FILENAME = 'wand.babylon';
  71559. return ViveController;
  71560. }(BABYLON.WebVRController));
  71561. BABYLON.ViveController = ViveController;
  71562. })(BABYLON || (BABYLON = {}));
  71563. //# sourceMappingURL=babylon.viveController.js.map
  71564. var BABYLON;
  71565. (function (BABYLON) {
  71566. /**
  71567. * Generic Controller
  71568. */
  71569. var GenericController = /** @class */ (function (_super) {
  71570. __extends(GenericController, _super);
  71571. /**
  71572. * Creates a new GenericController from a gamepad
  71573. * @param vrGamepad the gamepad that the controller should be created from
  71574. */
  71575. function GenericController(vrGamepad) {
  71576. return _super.call(this, vrGamepad) || this;
  71577. }
  71578. /**
  71579. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71580. * @param scene scene in which to add meshes
  71581. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71582. */
  71583. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71584. var _this = this;
  71585. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71586. _this._defaultModel = newMeshes[1];
  71587. _this.attachToMesh(_this._defaultModel);
  71588. if (meshLoaded) {
  71589. meshLoaded(_this._defaultModel);
  71590. }
  71591. });
  71592. };
  71593. /**
  71594. * Called once for each button that changed state since the last frame
  71595. * @param buttonIdx Which button index changed
  71596. * @param state New state of the button
  71597. * @param changes Which properties on the state changed since last frame
  71598. */
  71599. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71600. console.log("Button id: " + buttonIdx + "state: ");
  71601. console.dir(state);
  71602. };
  71603. /**
  71604. * Base Url for the controller model.
  71605. */
  71606. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71607. /**
  71608. * File name for the controller model.
  71609. */
  71610. GenericController.MODEL_FILENAME = 'generic.babylon';
  71611. return GenericController;
  71612. }(BABYLON.WebVRController));
  71613. BABYLON.GenericController = GenericController;
  71614. })(BABYLON || (BABYLON = {}));
  71615. //# sourceMappingURL=babylon.genericController.js.map
  71616. var BABYLON;
  71617. (function (BABYLON) {
  71618. /**
  71619. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71620. */
  71621. var LoadedMeshInfo = /** @class */ (function () {
  71622. function LoadedMeshInfo() {
  71623. /**
  71624. * Map of the button meshes contained in the controller
  71625. */
  71626. this.buttonMeshes = {};
  71627. /**
  71628. * Map of the axis meshes contained in the controller
  71629. */
  71630. this.axisMeshes = {};
  71631. }
  71632. return LoadedMeshInfo;
  71633. }());
  71634. /**
  71635. * Defines the WindowsMotionController object that the state of the windows motion controller
  71636. */
  71637. var WindowsMotionController = /** @class */ (function (_super) {
  71638. __extends(WindowsMotionController, _super);
  71639. /**
  71640. * Creates a new WindowsMotionController from a gamepad
  71641. * @param vrGamepad the gamepad that the controller should be created from
  71642. */
  71643. function WindowsMotionController(vrGamepad) {
  71644. var _this = _super.call(this, vrGamepad) || this;
  71645. _this._mapping = {
  71646. // Semantic button names
  71647. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71648. // A mapping of the button name to glTF model node name
  71649. // that should be transformed by button value.
  71650. buttonMeshNames: {
  71651. 'trigger': 'SELECT',
  71652. 'menu': 'MENU',
  71653. 'grip': 'GRASP',
  71654. 'thumbstick': 'THUMBSTICK_PRESS',
  71655. 'trackpad': 'TOUCHPAD_PRESS'
  71656. },
  71657. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71658. buttonObservableNames: {
  71659. 'trigger': 'onTriggerStateChangedObservable',
  71660. 'menu': 'onSecondaryButtonStateChangedObservable',
  71661. 'grip': 'onMainButtonStateChangedObservable',
  71662. 'thumbstick': 'onPadStateChangedObservable',
  71663. 'trackpad': 'onTrackpadChangedObservable'
  71664. },
  71665. // A mapping of the axis name to glTF model node name
  71666. // that should be transformed by axis value.
  71667. // This array mirrors the browserGamepad.axes array, such that
  71668. // the mesh corresponding to axis 0 is in this array index 0.
  71669. axisMeshNames: [
  71670. 'THUMBSTICK_X',
  71671. 'THUMBSTICK_Y',
  71672. 'TOUCHPAD_TOUCH_X',
  71673. 'TOUCHPAD_TOUCH_Y'
  71674. ],
  71675. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71676. };
  71677. /**
  71678. * Fired when the trackpad on this controller is clicked
  71679. */
  71680. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71681. /**
  71682. * Fired when the trackpad on this controller is modified
  71683. */
  71684. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71685. /**
  71686. * The current x and y values of this controller's trackpad
  71687. */
  71688. _this.trackpad = { x: 0, y: 0 };
  71689. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71690. _this._loadedMeshInfo = null;
  71691. return _this;
  71692. }
  71693. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71694. /**
  71695. * Fired when the trigger on this controller is modified
  71696. */
  71697. get: function () {
  71698. return this.onTriggerStateChangedObservable;
  71699. },
  71700. enumerable: true,
  71701. configurable: true
  71702. });
  71703. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71704. /**
  71705. * Fired when the menu button on this controller is modified
  71706. */
  71707. get: function () {
  71708. return this.onSecondaryButtonStateChangedObservable;
  71709. },
  71710. enumerable: true,
  71711. configurable: true
  71712. });
  71713. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71714. /**
  71715. * Fired when the grip button on this controller is modified
  71716. */
  71717. get: function () {
  71718. return this.onMainButtonStateChangedObservable;
  71719. },
  71720. enumerable: true,
  71721. configurable: true
  71722. });
  71723. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71724. /**
  71725. * Fired when the thumbstick button on this controller is modified
  71726. */
  71727. get: function () {
  71728. return this.onPadStateChangedObservable;
  71729. },
  71730. enumerable: true,
  71731. configurable: true
  71732. });
  71733. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71734. /**
  71735. * Fired when the touchpad button on this controller is modified
  71736. */
  71737. get: function () {
  71738. return this.onTrackpadChangedObservable;
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71744. /**
  71745. * Fired when the touchpad values on this controller are modified
  71746. */
  71747. get: function () {
  71748. return this.onTrackpadValuesChangedObservable;
  71749. },
  71750. enumerable: true,
  71751. configurable: true
  71752. });
  71753. /**
  71754. * Called once per frame by the engine.
  71755. */
  71756. WindowsMotionController.prototype.update = function () {
  71757. _super.prototype.update.call(this);
  71758. if (this.browserGamepad.axes) {
  71759. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71760. this.trackpad.x = this.browserGamepad["axes"][2];
  71761. this.trackpad.y = this.browserGamepad["axes"][3];
  71762. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71763. }
  71764. // Only need to animate axes if there is a loaded mesh
  71765. if (this._loadedMeshInfo) {
  71766. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71767. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71768. }
  71769. }
  71770. }
  71771. };
  71772. /**
  71773. * Called once for each button that changed state since the last frame
  71774. * @param buttonIdx Which button index changed
  71775. * @param state New state of the button
  71776. * @param changes Which properties on the state changed since last frame
  71777. */
  71778. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71779. var buttonName = this._mapping.buttons[buttonIdx];
  71780. if (!buttonName) {
  71781. return;
  71782. }
  71783. // Only emit events for buttons that we know how to map from index to name
  71784. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71785. if (observable) {
  71786. observable.notifyObservers(state);
  71787. }
  71788. this._lerpButtonTransform(buttonName, state.value);
  71789. };
  71790. /**
  71791. * Moves the buttons on the controller mesh based on their current state
  71792. * @param buttonName the name of the button to move
  71793. * @param buttonValue the value of the button which determines the buttons new position
  71794. */
  71795. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71796. // If there is no loaded mesh, there is nothing to transform.
  71797. if (!this._loadedMeshInfo) {
  71798. return;
  71799. }
  71800. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71801. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71802. return;
  71803. }
  71804. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71805. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71806. };
  71807. /**
  71808. * Moves the axis on the controller mesh based on its current state
  71809. * @param axis the index of the axis
  71810. * @param axisValue the value of the axis which determines the meshes new position
  71811. * @hidden
  71812. */
  71813. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71814. if (!this._loadedMeshInfo) {
  71815. return;
  71816. }
  71817. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71818. if (!meshInfo) {
  71819. return;
  71820. }
  71821. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71822. return;
  71823. }
  71824. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71825. var lerpValue = axisValue * 0.5 + 0.5;
  71826. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71827. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71828. };
  71829. /**
  71830. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71831. * @param scene scene in which to add meshes
  71832. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71833. */
  71834. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71835. var _this = this;
  71836. if (forceDefault === void 0) { forceDefault = false; }
  71837. var path;
  71838. var filename;
  71839. // Checking if GLB loader is present
  71840. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71841. // Determine the device specific folder based on the ID suffix
  71842. var device = 'default';
  71843. if (this.id && !forceDefault) {
  71844. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71845. device = ((match && match[0]) || device);
  71846. }
  71847. // Hand
  71848. if (this.hand === 'left') {
  71849. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71850. }
  71851. else { // Right is the default if no hand is specified
  71852. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71853. }
  71854. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71855. }
  71856. else {
  71857. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71858. path = BABYLON.GenericController.MODEL_BASE_URL;
  71859. filename = BABYLON.GenericController.MODEL_FILENAME;
  71860. }
  71861. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71862. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71863. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71864. if (!_this._loadedMeshInfo) {
  71865. return;
  71866. }
  71867. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71868. _this.attachToMesh(_this._defaultModel);
  71869. if (meshLoaded) {
  71870. meshLoaded(_this._defaultModel);
  71871. }
  71872. }, null, function (scene, message) {
  71873. BABYLON.Tools.Log(message);
  71874. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71875. if (!forceDefault) {
  71876. _this.initControllerMesh(scene, meshLoaded, true);
  71877. }
  71878. });
  71879. };
  71880. /**
  71881. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71882. * can be transformed by button presses and axes values, based on this._mapping.
  71883. *
  71884. * @param scene scene in which the meshes exist
  71885. * @param meshes list of meshes that make up the controller model to process
  71886. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71887. */
  71888. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71889. var loadedMeshInfo = null;
  71890. // Create a new mesh to contain the glTF hierarchy
  71891. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71892. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71893. var childMesh = null;
  71894. for (var i = 0; i < meshes.length; i++) {
  71895. var mesh = meshes[i];
  71896. if (!mesh.parent) {
  71897. // Exclude controller meshes from picking results
  71898. mesh.isPickable = false;
  71899. // Handle root node, attach to the new parentMesh
  71900. childMesh = mesh;
  71901. break;
  71902. }
  71903. }
  71904. if (childMesh) {
  71905. childMesh.setParent(parentMesh);
  71906. // Create our mesh info. Note that this method will always return non-null.
  71907. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71908. }
  71909. else {
  71910. BABYLON.Tools.Warn('Could not find root node in model file.');
  71911. }
  71912. return loadedMeshInfo;
  71913. };
  71914. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71915. var loadedMeshInfo = new LoadedMeshInfo();
  71916. var i;
  71917. loadedMeshInfo.rootNode = rootNode;
  71918. // Reset the caches
  71919. loadedMeshInfo.buttonMeshes = {};
  71920. loadedMeshInfo.axisMeshes = {};
  71921. // Button Meshes
  71922. for (i = 0; i < this._mapping.buttons.length; i++) {
  71923. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71924. if (!buttonMeshName) {
  71925. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71926. continue;
  71927. }
  71928. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71929. if (!buttonMesh) {
  71930. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71931. continue;
  71932. }
  71933. var buttonMeshInfo = {
  71934. index: i,
  71935. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71936. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71937. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71938. };
  71939. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71940. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71941. }
  71942. else {
  71943. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71944. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71945. '(VALUE: ' + !!buttonMeshInfo.value +
  71946. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71947. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71948. ')');
  71949. }
  71950. }
  71951. // Axis Meshes
  71952. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71953. var axisMeshName = this._mapping.axisMeshNames[i];
  71954. if (!axisMeshName) {
  71955. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71956. continue;
  71957. }
  71958. var axisMesh = getChildByName(rootNode, axisMeshName);
  71959. if (!axisMesh) {
  71960. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71961. continue;
  71962. }
  71963. var axisMeshInfo = {
  71964. index: i,
  71965. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71966. min: getImmediateChildByName(axisMesh, 'MIN'),
  71967. max: getImmediateChildByName(axisMesh, 'MAX')
  71968. };
  71969. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71970. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71971. }
  71972. else {
  71973. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71974. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71975. '(VALUE: ' + !!axisMeshInfo.value +
  71976. ', MIN: ' + !!axisMeshInfo.min +
  71977. ', MAX:' + !!axisMeshInfo.max +
  71978. ')');
  71979. }
  71980. }
  71981. // Pointing Ray
  71982. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71983. if (!loadedMeshInfo.pointingPoseNode) {
  71984. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71985. }
  71986. return loadedMeshInfo;
  71987. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71988. function getChildByName(node, name) {
  71989. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71990. }
  71991. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71992. function getImmediateChildByName(node, name) {
  71993. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71994. }
  71995. };
  71996. /**
  71997. * Gets the ray of the controller in the direction the controller is pointing
  71998. * @param length the length the resulting ray should be
  71999. * @returns a ray in the direction the controller is pointing
  72000. */
  72001. WindowsMotionController.prototype.getForwardRay = function (length) {
  72002. if (length === void 0) { length = 100; }
  72003. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72004. return _super.prototype.getForwardRay.call(this, length);
  72005. }
  72006. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72007. var origin = m.getTranslation();
  72008. var forward = new BABYLON.Vector3(0, 0, -1);
  72009. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72010. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72011. return new BABYLON.Ray(origin, direction, length);
  72012. };
  72013. /**
  72014. * Disposes of the controller
  72015. */
  72016. WindowsMotionController.prototype.dispose = function () {
  72017. _super.prototype.dispose.call(this);
  72018. this.onTrackpadChangedObservable.clear();
  72019. };
  72020. /**
  72021. * The base url used to load the left and right controller models
  72022. */
  72023. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72024. /**
  72025. * The name of the left controller model file
  72026. */
  72027. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72028. /**
  72029. * The name of the right controller model file
  72030. */
  72031. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72032. /**
  72033. * The controller name prefix for this controller type
  72034. */
  72035. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72036. /**
  72037. * The controller id pattern for this controller type
  72038. */
  72039. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72040. return WindowsMotionController;
  72041. }(BABYLON.WebVRController));
  72042. BABYLON.WindowsMotionController = WindowsMotionController;
  72043. })(BABYLON || (BABYLON = {}));
  72044. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. /**
  72048. * Gear VR Controller
  72049. */
  72050. var GearVRController = /** @class */ (function (_super) {
  72051. __extends(GearVRController, _super);
  72052. /**
  72053. * Creates a new GearVRController from a gamepad
  72054. * @param vrGamepad the gamepad that the controller should be created from
  72055. */
  72056. function GearVRController(vrGamepad) {
  72057. var _this = _super.call(this, vrGamepad) || this;
  72058. _this._buttonIndexToObservableNameMap = [
  72059. 'onTrackpadChangedObservable',
  72060. 'onTriggerStateChangedObservable' // Trigger
  72061. ];
  72062. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72063. return _this;
  72064. }
  72065. /**
  72066. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72067. * @param scene scene in which to add meshes
  72068. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72069. */
  72070. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72071. var _this = this;
  72072. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72073. _this._defaultModel = newMeshes[1];
  72074. _this.attachToMesh(_this._defaultModel);
  72075. if (meshLoaded) {
  72076. meshLoaded(_this._defaultModel);
  72077. }
  72078. });
  72079. };
  72080. /**
  72081. * Called once for each button that changed state since the last frame
  72082. * @param buttonIdx Which button index changed
  72083. * @param state New state of the button
  72084. * @param changes Which properties on the state changed since last frame
  72085. */
  72086. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72087. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72088. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72089. // Only emit events for buttons that we know how to map from index to observable
  72090. var observable = this[observableName];
  72091. if (observable) {
  72092. observable.notifyObservers(state);
  72093. }
  72094. }
  72095. };
  72096. /**
  72097. * Base Url for the controller model.
  72098. */
  72099. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72100. /**
  72101. * File name for the controller model.
  72102. */
  72103. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72104. /**
  72105. * Gamepad Id prefix used to identify this controller.
  72106. */
  72107. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72108. return GearVRController;
  72109. }(BABYLON.WebVRController));
  72110. BABYLON.GearVRController = GearVRController;
  72111. })(BABYLON || (BABYLON = {}));
  72112. //# sourceMappingURL=babylon.gearVRController.js.map
  72113. var BABYLON;
  72114. (function (BABYLON) {
  72115. /**
  72116. * Google Daydream controller
  72117. */
  72118. var DaydreamController = /** @class */ (function (_super) {
  72119. __extends(DaydreamController, _super);
  72120. /**
  72121. * Creates a new DaydreamController from a gamepad
  72122. * @param vrGamepad the gamepad that the controller should be created from
  72123. */
  72124. function DaydreamController(vrGamepad) {
  72125. var _this = _super.call(this, vrGamepad) || this;
  72126. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72127. return _this;
  72128. }
  72129. /**
  72130. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72131. * @param scene scene in which to add meshes
  72132. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72133. */
  72134. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72135. var _this = this;
  72136. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72137. _this._defaultModel = newMeshes[1];
  72138. _this.attachToMesh(_this._defaultModel);
  72139. if (meshLoaded) {
  72140. meshLoaded(_this._defaultModel);
  72141. }
  72142. });
  72143. };
  72144. /**
  72145. * Called once for each button that changed state since the last frame
  72146. * @param buttonIdx Which button index changed
  72147. * @param state New state of the button
  72148. * @param changes Which properties on the state changed since last frame
  72149. */
  72150. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72151. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72152. if (buttonIdx === 0) {
  72153. var observable = this.onTriggerStateChangedObservable;
  72154. if (observable) {
  72155. observable.notifyObservers(state);
  72156. }
  72157. }
  72158. else {
  72159. // If the app or home buttons are ever made available
  72160. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72161. }
  72162. };
  72163. /**
  72164. * Base Url for the controller model.
  72165. */
  72166. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72167. /**
  72168. * File name for the controller model.
  72169. */
  72170. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72171. /**
  72172. * Gamepad Id prefix used to identify Daydream Controller.
  72173. */
  72174. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72175. return DaydreamController;
  72176. }(BABYLON.WebVRController));
  72177. BABYLON.DaydreamController = DaydreamController;
  72178. })(BABYLON || (BABYLON = {}));
  72179. //# sourceMappingURL=babylon.daydreamController.js.map
  72180. var BABYLON;
  72181. (function (BABYLON) {
  72182. var FollowCamera = /** @class */ (function (_super) {
  72183. __extends(FollowCamera, _super);
  72184. function FollowCamera(name, position, scene, lockedTarget) {
  72185. if (lockedTarget === void 0) { lockedTarget = null; }
  72186. var _this = _super.call(this, name, position, scene) || this;
  72187. _this.radius = 12;
  72188. _this.rotationOffset = 0;
  72189. _this.heightOffset = 4;
  72190. _this.cameraAcceleration = 0.05;
  72191. _this.maxCameraSpeed = 20;
  72192. _this.lockedTarget = lockedTarget;
  72193. return _this;
  72194. }
  72195. FollowCamera.prototype.getRadians = function (degrees) {
  72196. return degrees * Math.PI / 180;
  72197. };
  72198. FollowCamera.prototype.follow = function (cameraTarget) {
  72199. if (!cameraTarget)
  72200. return;
  72201. var yRotation;
  72202. if (cameraTarget.rotationQuaternion) {
  72203. var rotMatrix = new BABYLON.Matrix();
  72204. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72205. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72206. }
  72207. else {
  72208. yRotation = cameraTarget.rotation.y;
  72209. }
  72210. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72211. var targetPosition = cameraTarget.getAbsolutePosition();
  72212. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72213. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72214. var dx = targetX - this.position.x;
  72215. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72216. var dz = (targetZ) - this.position.z;
  72217. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72218. var vy = dy * this.cameraAcceleration;
  72219. var vz = dz * this.cameraAcceleration * 2;
  72220. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72221. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72222. }
  72223. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72224. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72225. }
  72226. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72227. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72228. }
  72229. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72230. this.setTarget(targetPosition);
  72231. };
  72232. FollowCamera.prototype._checkInputs = function () {
  72233. _super.prototype._checkInputs.call(this);
  72234. if (this.lockedTarget) {
  72235. this.follow(this.lockedTarget);
  72236. }
  72237. };
  72238. FollowCamera.prototype.getClassName = function () {
  72239. return "FollowCamera";
  72240. };
  72241. __decorate([
  72242. BABYLON.serialize()
  72243. ], FollowCamera.prototype, "radius", void 0);
  72244. __decorate([
  72245. BABYLON.serialize()
  72246. ], FollowCamera.prototype, "rotationOffset", void 0);
  72247. __decorate([
  72248. BABYLON.serialize()
  72249. ], FollowCamera.prototype, "heightOffset", void 0);
  72250. __decorate([
  72251. BABYLON.serialize()
  72252. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72253. __decorate([
  72254. BABYLON.serialize()
  72255. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72256. __decorate([
  72257. BABYLON.serializeAsMeshReference("lockedTargetId")
  72258. ], FollowCamera.prototype, "lockedTarget", void 0);
  72259. return FollowCamera;
  72260. }(BABYLON.TargetCamera));
  72261. BABYLON.FollowCamera = FollowCamera;
  72262. var ArcFollowCamera = /** @class */ (function (_super) {
  72263. __extends(ArcFollowCamera, _super);
  72264. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72265. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72266. _this.alpha = alpha;
  72267. _this.beta = beta;
  72268. _this.radius = radius;
  72269. _this.target = target;
  72270. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72271. _this.follow();
  72272. return _this;
  72273. }
  72274. ArcFollowCamera.prototype.follow = function () {
  72275. if (!this.target) {
  72276. return;
  72277. }
  72278. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72279. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72280. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72281. var targetPosition = this.target.getAbsolutePosition();
  72282. this.position = targetPosition.add(this._cartesianCoordinates);
  72283. this.setTarget(targetPosition);
  72284. };
  72285. ArcFollowCamera.prototype._checkInputs = function () {
  72286. _super.prototype._checkInputs.call(this);
  72287. this.follow();
  72288. };
  72289. ArcFollowCamera.prototype.getClassName = function () {
  72290. return "ArcFollowCamera";
  72291. };
  72292. return ArcFollowCamera;
  72293. }(BABYLON.TargetCamera));
  72294. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72295. })(BABYLON || (BABYLON = {}));
  72296. //# sourceMappingURL=babylon.followCamera.js.map
  72297. var BABYLON;
  72298. (function (BABYLON) {
  72299. // We're mainly based on the logic defined into the FreeCamera code
  72300. var UniversalCamera = /** @class */ (function (_super) {
  72301. __extends(UniversalCamera, _super);
  72302. //-- end properties for backward compatibility for inputs
  72303. function UniversalCamera(name, position, scene) {
  72304. var _this = _super.call(this, name, position, scene) || this;
  72305. _this.inputs.addGamepad();
  72306. return _this;
  72307. }
  72308. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72309. //-- Begin properties for backward compatibility for inputs
  72310. get: function () {
  72311. var gamepad = this.inputs.attached["gamepad"];
  72312. if (gamepad)
  72313. return gamepad.gamepadAngularSensibility;
  72314. return 0;
  72315. },
  72316. set: function (value) {
  72317. var gamepad = this.inputs.attached["gamepad"];
  72318. if (gamepad)
  72319. gamepad.gamepadAngularSensibility = value;
  72320. },
  72321. enumerable: true,
  72322. configurable: true
  72323. });
  72324. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72325. get: function () {
  72326. var gamepad = this.inputs.attached["gamepad"];
  72327. if (gamepad)
  72328. return gamepad.gamepadMoveSensibility;
  72329. return 0;
  72330. },
  72331. set: function (value) {
  72332. var gamepad = this.inputs.attached["gamepad"];
  72333. if (gamepad)
  72334. gamepad.gamepadMoveSensibility = value;
  72335. },
  72336. enumerable: true,
  72337. configurable: true
  72338. });
  72339. UniversalCamera.prototype.getClassName = function () {
  72340. return "UniversalCamera";
  72341. };
  72342. return UniversalCamera;
  72343. }(BABYLON.TouchCamera));
  72344. BABYLON.UniversalCamera = UniversalCamera;
  72345. })(BABYLON || (BABYLON = {}));
  72346. //# sourceMappingURL=babylon.universalCamera.js.map
  72347. var BABYLON;
  72348. (function (BABYLON) {
  72349. // We're mainly based on the logic defined into the FreeCamera code
  72350. var GamepadCamera = /** @class */ (function (_super) {
  72351. __extends(GamepadCamera, _super);
  72352. //-- end properties for backward compatibility for inputs
  72353. function GamepadCamera(name, position, scene) {
  72354. return _super.call(this, name, position, scene) || this;
  72355. }
  72356. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72357. //-- Begin properties for backward compatibility for inputs
  72358. get: function () {
  72359. var gamepad = this.inputs.attached["gamepad"];
  72360. if (gamepad)
  72361. return gamepad.gamepadAngularSensibility;
  72362. return 0;
  72363. },
  72364. set: function (value) {
  72365. var gamepad = this.inputs.attached["gamepad"];
  72366. if (gamepad)
  72367. gamepad.gamepadAngularSensibility = value;
  72368. },
  72369. enumerable: true,
  72370. configurable: true
  72371. });
  72372. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72373. get: function () {
  72374. var gamepad = this.inputs.attached["gamepad"];
  72375. if (gamepad)
  72376. return gamepad.gamepadMoveSensibility;
  72377. return 0;
  72378. },
  72379. set: function (value) {
  72380. var gamepad = this.inputs.attached["gamepad"];
  72381. if (gamepad)
  72382. gamepad.gamepadMoveSensibility = value;
  72383. },
  72384. enumerable: true,
  72385. configurable: true
  72386. });
  72387. GamepadCamera.prototype.getClassName = function () {
  72388. return "GamepadCamera";
  72389. };
  72390. return GamepadCamera;
  72391. }(BABYLON.UniversalCamera));
  72392. BABYLON.GamepadCamera = GamepadCamera;
  72393. })(BABYLON || (BABYLON = {}));
  72394. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72395. var BABYLON;
  72396. (function (BABYLON) {
  72397. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72398. function PostProcessRenderPipelineManager() {
  72399. this._renderPipelines = {};
  72400. }
  72401. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72402. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72403. };
  72404. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72405. if (unique === void 0) { unique = false; }
  72406. var renderPipeline = this._renderPipelines[renderPipelineName];
  72407. if (!renderPipeline) {
  72408. return;
  72409. }
  72410. renderPipeline._attachCameras(cameras, unique);
  72411. };
  72412. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72413. var renderPipeline = this._renderPipelines[renderPipelineName];
  72414. if (!renderPipeline) {
  72415. return;
  72416. }
  72417. renderPipeline._detachCameras(cameras);
  72418. };
  72419. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72420. var renderPipeline = this._renderPipelines[renderPipelineName];
  72421. if (!renderPipeline) {
  72422. return;
  72423. }
  72424. renderPipeline._enableEffect(renderEffectName, cameras);
  72425. };
  72426. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72427. var renderPipeline = this._renderPipelines[renderPipelineName];
  72428. if (!renderPipeline) {
  72429. return;
  72430. }
  72431. renderPipeline._disableEffect(renderEffectName, cameras);
  72432. };
  72433. PostProcessRenderPipelineManager.prototype.update = function () {
  72434. for (var renderPipelineName in this._renderPipelines) {
  72435. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72436. var pipeline = this._renderPipelines[renderPipelineName];
  72437. if (!pipeline.isSupported) {
  72438. pipeline.dispose();
  72439. delete this._renderPipelines[renderPipelineName];
  72440. }
  72441. else {
  72442. pipeline._update();
  72443. }
  72444. }
  72445. }
  72446. };
  72447. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72448. for (var renderPipelineName in this._renderPipelines) {
  72449. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72450. var pipeline = this._renderPipelines[renderPipelineName];
  72451. pipeline._rebuild();
  72452. }
  72453. }
  72454. };
  72455. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72456. for (var renderPipelineName in this._renderPipelines) {
  72457. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72458. var pipeline = this._renderPipelines[renderPipelineName];
  72459. pipeline.dispose();
  72460. }
  72461. }
  72462. };
  72463. return PostProcessRenderPipelineManager;
  72464. }());
  72465. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72466. })(BABYLON || (BABYLON = {}));
  72467. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72468. var BABYLON;
  72469. (function (BABYLON) {
  72470. /**
  72471. * This represents a set of one or more post processes in Babylon.
  72472. * A post process can be used to apply a shader to a texture after it is rendered.
  72473. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72474. */
  72475. var PostProcessRenderEffect = /** @class */ (function () {
  72476. /**
  72477. * Instantiates a post process render effect.
  72478. * A post process can be used to apply a shader to a texture after it is rendered.
  72479. * @param engine The engine the effect is tied to
  72480. * @param name The name of the effect
  72481. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72482. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72483. */
  72484. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72485. this._name = name;
  72486. this._singleInstance = singleInstance || true;
  72487. this._getPostProcesses = getPostProcesses;
  72488. this._cameras = {};
  72489. this._indicesForCamera = {};
  72490. this._postProcesses = {};
  72491. }
  72492. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72493. /**
  72494. * Checks if all the post processes in the effect are supported.
  72495. */
  72496. get: function () {
  72497. for (var index in this._postProcesses) {
  72498. if (this._postProcesses.hasOwnProperty(index)) {
  72499. var pps = this._postProcesses[index];
  72500. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72501. if (!pps[ppIndex].isSupported) {
  72502. return false;
  72503. }
  72504. }
  72505. }
  72506. }
  72507. return true;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. /**
  72513. * Updates the current state of the effect
  72514. */
  72515. PostProcessRenderEffect.prototype._update = function () {
  72516. };
  72517. /**
  72518. * Attaches the effect on cameras
  72519. * @param cameras The camera to attach to.
  72520. */
  72521. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72522. var _this = this;
  72523. var cameraKey;
  72524. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72525. if (!cams) {
  72526. return;
  72527. }
  72528. for (var i = 0; i < cams.length; i++) {
  72529. var camera = cams[i];
  72530. var cameraName = camera.name;
  72531. if (this._singleInstance) {
  72532. cameraKey = 0;
  72533. }
  72534. else {
  72535. cameraKey = cameraName;
  72536. }
  72537. if (!this._postProcesses[cameraKey]) {
  72538. var postProcess = this._getPostProcesses();
  72539. if (postProcess) {
  72540. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72541. }
  72542. }
  72543. if (!this._indicesForCamera[cameraName]) {
  72544. this._indicesForCamera[cameraName] = [];
  72545. }
  72546. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72547. var index = camera.attachPostProcess(postProcess);
  72548. _this._indicesForCamera[cameraName].push(index);
  72549. });
  72550. if (!this._cameras[cameraName]) {
  72551. this._cameras[cameraName] = camera;
  72552. }
  72553. }
  72554. };
  72555. /**
  72556. * Detatches the effect on cameras
  72557. * @param cameras The camera to detatch from.
  72558. */
  72559. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72560. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72561. if (!cams) {
  72562. return;
  72563. }
  72564. for (var i = 0; i < cams.length; i++) {
  72565. var camera = cams[i];
  72566. var cameraName = camera.name;
  72567. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72568. camera.detachPostProcess(postProcess);
  72569. });
  72570. if (this._cameras[cameraName]) {
  72571. //this._indicesForCamera.splice(index, 1);
  72572. this._cameras[cameraName] = null;
  72573. }
  72574. }
  72575. };
  72576. /**
  72577. * Enables the effect on given cameras
  72578. * @param cameras The camera to enable.
  72579. */
  72580. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72581. var _this = this;
  72582. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72583. if (!cams) {
  72584. return;
  72585. }
  72586. for (var i = 0; i < cams.length; i++) {
  72587. var camera = cams[i];
  72588. var cameraName = camera.name;
  72589. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72590. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72591. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72592. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72593. });
  72594. }
  72595. }
  72596. }
  72597. };
  72598. /**
  72599. * Disables the effect on the given cameras
  72600. * @param cameras The camera to disable.
  72601. */
  72602. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72603. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72604. if (!cams) {
  72605. return;
  72606. }
  72607. for (var i = 0; i < cams.length; i++) {
  72608. var camera = cams[i];
  72609. var cameraName = camera.name;
  72610. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72611. camera.detachPostProcess(postProcess);
  72612. });
  72613. }
  72614. };
  72615. /**
  72616. * Gets a list of the post processes contained in the effect.
  72617. * @param camera The camera to get the post processes on.
  72618. * @returns The list of the post processes in the effect.
  72619. */
  72620. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72621. if (this._singleInstance) {
  72622. return this._postProcesses[0];
  72623. }
  72624. else {
  72625. if (!camera) {
  72626. return null;
  72627. }
  72628. return this._postProcesses[camera.name];
  72629. }
  72630. };
  72631. return PostProcessRenderEffect;
  72632. }());
  72633. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72634. })(BABYLON || (BABYLON = {}));
  72635. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72636. var BABYLON;
  72637. (function (BABYLON) {
  72638. var PostProcessRenderPipeline = /** @class */ (function () {
  72639. function PostProcessRenderPipeline(engine, name) {
  72640. this.engine = engine;
  72641. this._name = name;
  72642. this._renderEffects = {};
  72643. this._renderEffectsForIsolatedPass = new Array();
  72644. this._cameras = [];
  72645. }
  72646. PostProcessRenderPipeline.prototype.getClassName = function () {
  72647. return "PostProcessRenderPipeline";
  72648. };
  72649. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72650. get: function () {
  72651. for (var renderEffectName in this._renderEffects) {
  72652. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72653. if (!this._renderEffects[renderEffectName].isSupported) {
  72654. return false;
  72655. }
  72656. }
  72657. }
  72658. return true;
  72659. },
  72660. enumerable: true,
  72661. configurable: true
  72662. });
  72663. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72664. this._renderEffects[renderEffect._name] = renderEffect;
  72665. };
  72666. // private
  72667. PostProcessRenderPipeline.prototype._rebuild = function () {
  72668. };
  72669. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72670. var renderEffects = this._renderEffects[renderEffectName];
  72671. if (!renderEffects) {
  72672. return;
  72673. }
  72674. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72675. };
  72676. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72677. var renderEffects = this._renderEffects[renderEffectName];
  72678. if (!renderEffects) {
  72679. return;
  72680. }
  72681. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72682. };
  72683. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72684. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72685. if (!cams) {
  72686. return;
  72687. }
  72688. var indicesToDelete = [];
  72689. var i;
  72690. for (i = 0; i < cams.length; i++) {
  72691. var camera = cams[i];
  72692. var cameraName = camera.name;
  72693. if (this._cameras.indexOf(camera) === -1) {
  72694. this._cameras[cameraName] = camera;
  72695. }
  72696. else if (unique) {
  72697. indicesToDelete.push(i);
  72698. }
  72699. }
  72700. for (i = 0; i < indicesToDelete.length; i++) {
  72701. cameras.splice(indicesToDelete[i], 1);
  72702. }
  72703. for (var renderEffectName in this._renderEffects) {
  72704. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72705. this._renderEffects[renderEffectName]._attachCameras(cams);
  72706. }
  72707. }
  72708. };
  72709. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72710. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72711. if (!cams) {
  72712. return;
  72713. }
  72714. for (var renderEffectName in this._renderEffects) {
  72715. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72716. this._renderEffects[renderEffectName]._detachCameras(cams);
  72717. }
  72718. }
  72719. for (var i = 0; i < cams.length; i++) {
  72720. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72721. }
  72722. };
  72723. PostProcessRenderPipeline.prototype._update = function () {
  72724. for (var renderEffectName in this._renderEffects) {
  72725. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72726. this._renderEffects[renderEffectName]._update();
  72727. }
  72728. }
  72729. for (var i = 0; i < this._cameras.length; i++) {
  72730. var cameraName = this._cameras[i].name;
  72731. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72732. this._renderEffectsForIsolatedPass[cameraName]._update();
  72733. }
  72734. }
  72735. };
  72736. PostProcessRenderPipeline.prototype._reset = function () {
  72737. this._renderEffects = {};
  72738. this._renderEffectsForIsolatedPass = new Array();
  72739. };
  72740. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72741. // 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)
  72742. var effectKeys = Object.keys(this._renderEffects);
  72743. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72744. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72745. if (postProcesses) {
  72746. postProcesses[0].samples = sampleCount;
  72747. return true;
  72748. }
  72749. }
  72750. return false;
  72751. };
  72752. PostProcessRenderPipeline.prototype.dispose = function () {
  72753. // Must be implemented by children
  72754. };
  72755. __decorate([
  72756. BABYLON.serialize()
  72757. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72758. return PostProcessRenderPipeline;
  72759. }());
  72760. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72761. })(BABYLON || (BABYLON = {}));
  72762. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72763. var BABYLON;
  72764. (function (BABYLON) {
  72765. /**
  72766. * This represents a depth renderer in Babylon.
  72767. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72768. */
  72769. var DepthRenderer = /** @class */ (function () {
  72770. /**
  72771. * Instantiates a depth renderer
  72772. * @param scene The scene the renderer belongs to
  72773. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72774. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72775. */
  72776. function DepthRenderer(scene, type, camera) {
  72777. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72778. if (camera === void 0) { camera = null; }
  72779. var _this = this;
  72780. this._scene = scene;
  72781. this._camera = camera;
  72782. var engine = scene.getEngine();
  72783. // Render target
  72784. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72785. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72786. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72787. this._depthMap.refreshRate = 1;
  72788. this._depthMap.renderParticles = false;
  72789. this._depthMap.renderList = null;
  72790. // Camera to get depth map from to support multiple concurrent cameras
  72791. this._depthMap.activeCamera = this._camera;
  72792. this._depthMap.ignoreCameraViewport = true;
  72793. this._depthMap.useCameraPostProcesses = false;
  72794. // set default depth value to 1.0 (far away)
  72795. this._depthMap.onClearObservable.add(function (engine) {
  72796. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72797. });
  72798. // Custom render function
  72799. var renderSubMesh = function (subMesh) {
  72800. var mesh = subMesh.getRenderingMesh();
  72801. var scene = _this._scene;
  72802. var engine = scene.getEngine();
  72803. var material = subMesh.getMaterial();
  72804. if (!material) {
  72805. return;
  72806. }
  72807. // Culling and reverse (right handed system)
  72808. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72809. // Managing instances
  72810. var batch = mesh._getInstancesRenderList(subMesh._id);
  72811. if (batch.mustReturn) {
  72812. return;
  72813. }
  72814. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72815. var camera = _this._camera || scene.activeCamera;
  72816. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72817. engine.enableEffect(_this._effect);
  72818. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72819. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72820. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72821. // Alpha test
  72822. if (material && material.needAlphaTesting()) {
  72823. var alphaTexture = material.getAlphaTestTexture();
  72824. if (alphaTexture) {
  72825. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72826. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72827. }
  72828. }
  72829. // Bones
  72830. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72831. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72832. }
  72833. // Draw
  72834. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72835. }
  72836. };
  72837. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72838. var index;
  72839. if (depthOnlySubMeshes.length) {
  72840. engine.setColorWrite(false);
  72841. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72842. renderSubMesh(depthOnlySubMeshes.data[index]);
  72843. }
  72844. engine.setColorWrite(true);
  72845. }
  72846. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72847. renderSubMesh(opaqueSubMeshes.data[index]);
  72848. }
  72849. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72850. renderSubMesh(alphaTestSubMeshes.data[index]);
  72851. }
  72852. };
  72853. }
  72854. /**
  72855. * Creates the depth rendering effect and checks if the effect is ready.
  72856. * @param subMesh The submesh to be used to render the depth map of
  72857. * @param useInstances If multiple world instances should be used
  72858. * @returns if the depth renderer is ready to render the depth map
  72859. */
  72860. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72861. var material = subMesh.getMaterial();
  72862. if (material.disableDepthWrite) {
  72863. return false;
  72864. }
  72865. var defines = [];
  72866. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72867. var mesh = subMesh.getMesh();
  72868. // Alpha test
  72869. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72870. defines.push("#define ALPHATEST");
  72871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72872. attribs.push(BABYLON.VertexBuffer.UVKind);
  72873. defines.push("#define UV1");
  72874. }
  72875. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72876. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72877. defines.push("#define UV2");
  72878. }
  72879. }
  72880. // Bones
  72881. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72884. if (mesh.numBoneInfluencers > 4) {
  72885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72887. }
  72888. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72889. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72890. }
  72891. else {
  72892. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72893. }
  72894. // Instances
  72895. if (useInstances) {
  72896. defines.push("#define INSTANCES");
  72897. attribs.push("world0");
  72898. attribs.push("world1");
  72899. attribs.push("world2");
  72900. attribs.push("world3");
  72901. }
  72902. // Get correct effect
  72903. var join = defines.join("\n");
  72904. if (this._cachedDefines !== join) {
  72905. this._cachedDefines = join;
  72906. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72907. }
  72908. return this._effect.isReady();
  72909. };
  72910. /**
  72911. * Gets the texture which the depth map will be written to.
  72912. * @returns The depth map texture
  72913. */
  72914. DepthRenderer.prototype.getDepthMap = function () {
  72915. return this._depthMap;
  72916. };
  72917. /**
  72918. * Disposes of the depth renderer.
  72919. */
  72920. DepthRenderer.prototype.dispose = function () {
  72921. this._depthMap.dispose();
  72922. };
  72923. return DepthRenderer;
  72924. }());
  72925. BABYLON.DepthRenderer = DepthRenderer;
  72926. })(BABYLON || (BABYLON = {}));
  72927. //# sourceMappingURL=babylon.depthRenderer.js.map
  72928. var BABYLON;
  72929. (function (BABYLON) {
  72930. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72931. __extends(SSAORenderingPipeline, _super);
  72932. /**
  72933. * @constructor
  72934. * @param {string} name - The rendering pipeline name
  72935. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72936. * @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 }
  72937. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72938. */
  72939. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72940. var _this = _super.call(this, scene.getEngine(), name) || this;
  72941. // Members
  72942. /**
  72943. * The PassPostProcess id in the pipeline that contains the original scene color
  72944. */
  72945. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72946. /**
  72947. * The SSAO PostProcess id in the pipeline
  72948. */
  72949. _this.SSAORenderEffect = "SSAORenderEffect";
  72950. /**
  72951. * The horizontal blur PostProcess id in the pipeline
  72952. */
  72953. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72954. /**
  72955. * The vertical blur PostProcess id in the pipeline
  72956. */
  72957. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72958. /**
  72959. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72960. */
  72961. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72962. /**
  72963. * The output strength of the SSAO post-process. Default value is 1.0.
  72964. */
  72965. _this.totalStrength = 1.0;
  72966. /**
  72967. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72968. */
  72969. _this.radius = 0.0001;
  72970. /**
  72971. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72972. * Must not be equal to fallOff and superior to fallOff.
  72973. * Default value is 0.975
  72974. */
  72975. _this.area = 0.0075;
  72976. /**
  72977. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72978. * Must not be equal to area and inferior to area.
  72979. * Default value is 0.0
  72980. */
  72981. _this.fallOff = 0.000001;
  72982. /**
  72983. * The base color of the SSAO post-process
  72984. * The final result is "base + ssao" between [0, 1]
  72985. */
  72986. _this.base = 0.5;
  72987. _this._firstUpdate = true;
  72988. _this._scene = scene;
  72989. // Set up assets
  72990. _this._createRandomTexture();
  72991. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72992. var ssaoRatio = ratio.ssaoRatio || ratio;
  72993. var combineRatio = ratio.combineRatio || ratio;
  72994. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72995. _this._createSSAOPostProcess(ssaoRatio);
  72996. _this._createBlurPostProcess(ssaoRatio);
  72997. _this._createSSAOCombinePostProcess(combineRatio);
  72998. // Set up pipeline
  72999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73002. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73003. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73004. // Finish
  73005. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73006. if (cameras)
  73007. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73008. return _this;
  73009. }
  73010. // Public Methods
  73011. /**
  73012. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73013. */
  73014. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73015. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73016. for (var i = 0; i < this._scene.cameras.length; i++) {
  73017. var camera = this._scene.cameras[i];
  73018. this._originalColorPostProcess.dispose(camera);
  73019. this._ssaoPostProcess.dispose(camera);
  73020. this._blurHPostProcess.dispose(camera);
  73021. this._blurVPostProcess.dispose(camera);
  73022. this._ssaoCombinePostProcess.dispose(camera);
  73023. }
  73024. this._randomTexture.dispose();
  73025. if (disableDepthRender)
  73026. this._scene.disableDepthRenderer();
  73027. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73028. _super.prototype.dispose.call(this);
  73029. };
  73030. // Private Methods
  73031. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73032. var _this = this;
  73033. var size = 16;
  73034. 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);
  73035. 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);
  73036. this._blurHPostProcess.onActivateObservable.add(function () {
  73037. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73038. _this._blurHPostProcess.kernel = size * dw;
  73039. });
  73040. this._blurVPostProcess.onActivateObservable.add(function () {
  73041. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73042. _this._blurVPostProcess.kernel = size * dw;
  73043. });
  73044. };
  73045. SSAORenderingPipeline.prototype._rebuild = function () {
  73046. this._firstUpdate = true;
  73047. _super.prototype._rebuild.call(this);
  73048. };
  73049. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73050. var _this = this;
  73051. var numSamples = 16;
  73052. var sampleSphere = [
  73053. 0.5381, 0.1856, -0.4319,
  73054. 0.1379, 0.2486, 0.4430,
  73055. 0.3371, 0.5679, -0.0057,
  73056. -0.6999, -0.0451, -0.0019,
  73057. 0.0689, -0.1598, -0.8547,
  73058. 0.0560, 0.0069, -0.1843,
  73059. -0.0146, 0.1402, 0.0762,
  73060. 0.0100, -0.1924, -0.0344,
  73061. -0.3577, -0.5301, -0.4358,
  73062. -0.3169, 0.1063, 0.0158,
  73063. 0.0103, -0.5869, 0.0046,
  73064. -0.0897, -0.4940, 0.3287,
  73065. 0.7119, -0.0154, -0.0918,
  73066. -0.0533, 0.0596, -0.5411,
  73067. 0.0352, -0.0631, 0.5460,
  73068. -0.4776, 0.2847, -0.0271
  73069. ];
  73070. var samplesFactor = 1.0 / numSamples;
  73071. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73072. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73073. "area", "fallOff", "base", "range", "viewport"
  73074. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73075. this._ssaoPostProcess.onApply = function (effect) {
  73076. if (_this._firstUpdate) {
  73077. effect.setArray3("sampleSphere", sampleSphere);
  73078. effect.setFloat("samplesFactor", samplesFactor);
  73079. effect.setFloat("randTextureTiles", 4.0);
  73080. }
  73081. effect.setFloat("totalStrength", _this.totalStrength);
  73082. effect.setFloat("radius", _this.radius);
  73083. effect.setFloat("area", _this.area);
  73084. effect.setFloat("fallOff", _this.fallOff);
  73085. effect.setFloat("base", _this.base);
  73086. effect.setTexture("textureSampler", _this._depthTexture);
  73087. effect.setTexture("randomSampler", _this._randomTexture);
  73088. };
  73089. };
  73090. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73091. var _this = this;
  73092. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73093. this._ssaoCombinePostProcess.onApply = function (effect) {
  73094. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73095. };
  73096. };
  73097. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73098. var size = 512;
  73099. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73100. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73101. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73102. var context = this._randomTexture.getContext();
  73103. var rand = function (min, max) {
  73104. return Math.random() * (max - min) + min;
  73105. };
  73106. var randVector = BABYLON.Vector3.Zero();
  73107. for (var x = 0; x < size; x++) {
  73108. for (var y = 0; y < size; y++) {
  73109. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73110. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73111. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73112. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73113. context.fillRect(x, y, 1, 1);
  73114. }
  73115. }
  73116. this._randomTexture.update(false);
  73117. };
  73118. __decorate([
  73119. BABYLON.serialize()
  73120. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73121. __decorate([
  73122. BABYLON.serialize()
  73123. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73124. __decorate([
  73125. BABYLON.serialize()
  73126. ], SSAORenderingPipeline.prototype, "area", void 0);
  73127. __decorate([
  73128. BABYLON.serialize()
  73129. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73130. __decorate([
  73131. BABYLON.serialize()
  73132. ], SSAORenderingPipeline.prototype, "base", void 0);
  73133. return SSAORenderingPipeline;
  73134. }(BABYLON.PostProcessRenderPipeline));
  73135. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73136. })(BABYLON || (BABYLON = {}));
  73137. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73138. var BABYLON;
  73139. (function (BABYLON) {
  73140. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73141. __extends(SSAO2RenderingPipeline, _super);
  73142. /**
  73143. * @constructor
  73144. * @param {string} name - The rendering pipeline name
  73145. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73146. * @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 }
  73147. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73148. */
  73149. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73150. var _this = _super.call(this, scene.getEngine(), name) || this;
  73151. // Members
  73152. /**
  73153. * The PassPostProcess id in the pipeline that contains the original scene color
  73154. */
  73155. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73156. /**
  73157. * The SSAO PostProcess id in the pipeline
  73158. */
  73159. _this.SSAORenderEffect = "SSAORenderEffect";
  73160. /**
  73161. * The horizontal blur PostProcess id in the pipeline
  73162. */
  73163. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73164. /**
  73165. * The vertical blur PostProcess id in the pipeline
  73166. */
  73167. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73168. /**
  73169. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73170. */
  73171. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73172. /**
  73173. * The output strength of the SSAO post-process. Default value is 1.0.
  73174. */
  73175. _this.totalStrength = 1.0;
  73176. /**
  73177. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73178. */
  73179. _this.maxZ = 100.0;
  73180. /**
  73181. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73182. */
  73183. _this.minZAspect = 0.2;
  73184. /**
  73185. * Number of samples used for the SSAO calculations. Default value is 8
  73186. */
  73187. _this._samples = 8;
  73188. /**
  73189. * Are we using bilateral blur ?
  73190. */
  73191. _this._expensiveBlur = true;
  73192. /**
  73193. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73194. */
  73195. _this.radius = 2.0;
  73196. /**
  73197. * The base color of the SSAO post-process
  73198. * The final result is "base + ssao" between [0, 1]
  73199. */
  73200. _this.base = 0.1;
  73201. _this._firstUpdate = true;
  73202. _this._scene = scene;
  73203. _this._ratio = ratio;
  73204. if (!_this.isSupported) {
  73205. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73206. return _this;
  73207. }
  73208. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73209. var blurRatio = _this._ratio.blurRatio || ratio;
  73210. // Set up assets
  73211. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73212. _this._createRandomTexture();
  73213. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73214. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73215. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73216. _this._createSSAOPostProcess(1.0);
  73217. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73218. _this._createSSAOCombinePostProcess(blurRatio);
  73219. // Set up pipeline
  73220. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73221. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73222. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73223. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73224. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73225. // Finish
  73226. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73227. if (cameras)
  73228. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73229. return _this;
  73230. }
  73231. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73232. get: function () {
  73233. return this._samples;
  73234. },
  73235. set: function (n) {
  73236. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73237. this._samples = n;
  73238. this._sampleSphere = this._generateHemisphere();
  73239. this._firstUpdate = true;
  73240. },
  73241. enumerable: true,
  73242. configurable: true
  73243. });
  73244. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73245. get: function () {
  73246. return this._expensiveBlur;
  73247. },
  73248. set: function (b) {
  73249. 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"]);
  73250. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73251. this._expensiveBlur = b;
  73252. this._firstUpdate = true;
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73258. /**
  73259. * Support test.
  73260. */
  73261. get: function () {
  73262. var engine = BABYLON.Engine.LastCreatedEngine;
  73263. if (!engine) {
  73264. return false;
  73265. }
  73266. return engine.getCaps().drawBuffersExtension;
  73267. },
  73268. enumerable: true,
  73269. configurable: true
  73270. });
  73271. // Public Methods
  73272. /**
  73273. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73274. */
  73275. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73276. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73277. for (var i = 0; i < this._scene.cameras.length; i++) {
  73278. var camera = this._scene.cameras[i];
  73279. this._originalColorPostProcess.dispose(camera);
  73280. this._ssaoPostProcess.dispose(camera);
  73281. this._blurHPostProcess.dispose(camera);
  73282. this._blurVPostProcess.dispose(camera);
  73283. this._ssaoCombinePostProcess.dispose(camera);
  73284. }
  73285. this._randomTexture.dispose();
  73286. if (disableGeometryBufferRenderer)
  73287. this._scene.disableGeometryBufferRenderer();
  73288. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73289. _super.prototype.dispose.call(this);
  73290. };
  73291. // Private Methods
  73292. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73293. var _this = this;
  73294. this._samplerOffsets = [];
  73295. var expensive = this.expensiveBlur;
  73296. for (var i = -8; i < 8; i++) {
  73297. this._samplerOffsets.push(i * 2 + 0.5);
  73298. }
  73299. 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");
  73300. this._blurHPostProcess.onApply = function (effect) {
  73301. if (!_this._scene.activeCamera) {
  73302. return;
  73303. }
  73304. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73305. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73306. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73307. effect.setFloat("radius", _this.radius);
  73308. effect.setTexture("depthSampler", _this._depthTexture);
  73309. if (_this._firstUpdate) {
  73310. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73311. }
  73312. };
  73313. 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");
  73314. this._blurVPostProcess.onApply = function (effect) {
  73315. if (!_this._scene.activeCamera) {
  73316. return;
  73317. }
  73318. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73319. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73320. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73321. effect.setFloat("radius", _this.radius);
  73322. effect.setTexture("depthSampler", _this._depthTexture);
  73323. if (_this._firstUpdate) {
  73324. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73325. _this._firstUpdate = false;
  73326. }
  73327. };
  73328. };
  73329. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73330. this._firstUpdate = true;
  73331. _super.prototype._rebuild.call(this);
  73332. };
  73333. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73334. var numSamples = this.samples;
  73335. var result = [];
  73336. var vector, scale;
  73337. var rand = function (min, max) {
  73338. return Math.random() * (max - min) + min;
  73339. };
  73340. var i = 0;
  73341. while (i < numSamples) {
  73342. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73343. vector.normalize();
  73344. scale = i / numSamples;
  73345. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73346. vector.scaleInPlace(scale);
  73347. result.push(vector.x, vector.y, vector.z);
  73348. i++;
  73349. }
  73350. return result;
  73351. };
  73352. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73353. var _this = this;
  73354. var numSamples = this.samples;
  73355. this._sampleSphere = this._generateHemisphere();
  73356. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73357. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73358. "base", "range", "projection", "near", "far", "texelSize",
  73359. "xViewport", "yViewport", "maxZ", "minZAspect"
  73360. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73361. this._ssaoPostProcess.onApply = function (effect) {
  73362. if (_this._firstUpdate) {
  73363. effect.setArray3("sampleSphere", _this._sampleSphere);
  73364. effect.setFloat("randTextureTiles", 4.0);
  73365. }
  73366. if (!_this._scene.activeCamera) {
  73367. return;
  73368. }
  73369. effect.setFloat("samplesFactor", 1 / _this.samples);
  73370. effect.setFloat("totalStrength", _this.totalStrength);
  73371. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73372. effect.setFloat("radius", _this.radius);
  73373. effect.setFloat("maxZ", _this.maxZ);
  73374. effect.setFloat("minZAspect", _this.minZAspect);
  73375. effect.setFloat("base", _this.base);
  73376. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73377. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73378. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73379. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73380. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73381. effect.setTexture("textureSampler", _this._depthTexture);
  73382. effect.setTexture("normalSampler", _this._normalTexture);
  73383. effect.setTexture("randomSampler", _this._randomTexture);
  73384. };
  73385. };
  73386. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73387. var _this = this;
  73388. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73389. this._ssaoCombinePostProcess.onApply = function (effect) {
  73390. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73391. };
  73392. };
  73393. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73394. var size = 512;
  73395. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73396. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73397. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73398. var context = this._randomTexture.getContext();
  73399. var rand = function (min, max) {
  73400. return Math.random() * (max - min) + min;
  73401. };
  73402. var randVector = BABYLON.Vector3.Zero();
  73403. for (var x = 0; x < size; x++) {
  73404. for (var y = 0; y < size; y++) {
  73405. randVector.x = rand(0.0, 1.0);
  73406. randVector.y = rand(0.0, 1.0);
  73407. randVector.z = 0.0;
  73408. randVector.normalize();
  73409. randVector.scaleInPlace(255);
  73410. randVector.x = Math.floor(randVector.x);
  73411. randVector.y = Math.floor(randVector.y);
  73412. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73413. context.fillRect(x, y, 1, 1);
  73414. }
  73415. }
  73416. this._randomTexture.update(false);
  73417. };
  73418. /**
  73419. * Serialize the rendering pipeline (Used when exporting)
  73420. * @returns the serialized object
  73421. */
  73422. SSAO2RenderingPipeline.prototype.serialize = function () {
  73423. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73424. serializationObject.customType = "SSAO2RenderingPipeline";
  73425. return serializationObject;
  73426. };
  73427. /**
  73428. * Parse the serialized pipeline
  73429. * @param source Source pipeline.
  73430. * @param scene The scene to load the pipeline to.
  73431. * @param rootUrl The URL of the serialized pipeline.
  73432. * @returns An instantiated pipeline from the serialized object.
  73433. */
  73434. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73435. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73436. };
  73437. __decorate([
  73438. BABYLON.serialize()
  73439. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73440. __decorate([
  73441. BABYLON.serialize()
  73442. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73443. __decorate([
  73444. BABYLON.serialize()
  73445. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73446. __decorate([
  73447. BABYLON.serialize("samples")
  73448. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73449. __decorate([
  73450. BABYLON.serialize()
  73451. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73452. __decorate([
  73453. BABYLON.serialize("expensiveBlur")
  73454. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73455. __decorate([
  73456. BABYLON.serialize()
  73457. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73458. __decorate([
  73459. BABYLON.serialize()
  73460. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73461. return SSAO2RenderingPipeline;
  73462. }(BABYLON.PostProcessRenderPipeline));
  73463. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73464. })(BABYLON || (BABYLON = {}));
  73465. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73466. // BABYLON.JS Chromatic Aberration GLSL Shader
  73467. // Author: Olivier Guyot
  73468. // Separates very slightly R, G and B colors on the edges of the screen
  73469. // Inspired by Francois Tarlier & Martins Upitis
  73470. var BABYLON;
  73471. (function (BABYLON) {
  73472. var LensRenderingPipeline = /** @class */ (function (_super) {
  73473. __extends(LensRenderingPipeline, _super);
  73474. /**
  73475. * @constructor
  73476. *
  73477. * Effect parameters are as follow:
  73478. * {
  73479. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73480. * edge_blur: number; // from 0 to x (1 for realism)
  73481. * distortion: number; // from 0 to x (1 for realism)
  73482. * grain_amount: number; // from 0 to 1
  73483. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73484. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73485. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73486. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73487. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73488. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73489. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73490. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73491. * }
  73492. * Note: if an effect parameter is unset, effect is disabled
  73493. *
  73494. * @param {string} name - The rendering pipeline name
  73495. * @param {object} parameters - An object containing all parameters (see above)
  73496. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73497. * @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)
  73498. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73499. */
  73500. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73501. if (ratio === void 0) { ratio = 1.0; }
  73502. var _this = _super.call(this, scene.getEngine(), name) || this;
  73503. // Lens effects can be of the following:
  73504. // - chromatic aberration (slight shift of RGB colors)
  73505. // - blur on the edge of the lens
  73506. // - lens distortion
  73507. // - depth-of-field blur & highlights enhancing
  73508. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73509. // - grain effect (noise or custom texture)
  73510. // Two additional texture samplers are needed:
  73511. // - depth map (for depth-of-field)
  73512. // - grain texture
  73513. /**
  73514. * The chromatic aberration PostProcess id in the pipeline
  73515. */
  73516. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73517. /**
  73518. * The highlights enhancing PostProcess id in the pipeline
  73519. */
  73520. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73521. /**
  73522. * The depth-of-field PostProcess id in the pipeline
  73523. */
  73524. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73525. _this._scene = scene;
  73526. // Fetch texture samplers
  73527. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73528. if (parameters.grain_texture) {
  73529. _this._grainTexture = parameters.grain_texture;
  73530. }
  73531. else {
  73532. _this._createGrainTexture();
  73533. }
  73534. // save parameters
  73535. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73536. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73537. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73538. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73539. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73540. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73541. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73542. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73543. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73544. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73545. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73546. // Create effects
  73547. _this._createChromaticAberrationPostProcess(ratio);
  73548. _this._createHighlightsPostProcess(ratio);
  73549. _this._createDepthOfFieldPostProcess(ratio / 4);
  73550. // Set up pipeline
  73551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73554. if (_this._highlightsGain === -1) {
  73555. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73556. }
  73557. // Finish
  73558. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73559. if (cameras) {
  73560. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73561. }
  73562. return _this;
  73563. }
  73564. // public methods (self explanatory)
  73565. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73566. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73567. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73568. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73569. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73570. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73571. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73572. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73573. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73574. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73575. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73576. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73577. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73578. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73579. };
  73580. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73581. this._highlightsPostProcess.updateEffect();
  73582. };
  73583. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73584. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73585. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73586. this._highlightsGain = amount;
  73587. };
  73588. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73589. if (this._highlightsGain === -1) {
  73590. this._highlightsGain = 1.0;
  73591. }
  73592. this._highlightsThreshold = amount;
  73593. };
  73594. LensRenderingPipeline.prototype.disableHighlights = function () {
  73595. this._highlightsGain = -1;
  73596. };
  73597. /**
  73598. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73599. */
  73600. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73601. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73602. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73603. this._chromaticAberrationPostProcess = null;
  73604. this._highlightsPostProcess = null;
  73605. this._depthOfFieldPostProcess = null;
  73606. this._grainTexture.dispose();
  73607. if (disableDepthRender)
  73608. this._scene.disableDepthRenderer();
  73609. };
  73610. // colors shifting and distortion
  73611. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73612. var _this = this;
  73613. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73614. [], // samplers
  73615. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73616. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73617. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73618. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73619. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73620. effect.setFloat('radialIntensity', 1);
  73621. effect.setFloat2('direction', 17, 17);
  73622. effect.setFloat2('centerPosition', 0.5, 0.5);
  73623. };
  73624. };
  73625. // highlights enhancing
  73626. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73627. var _this = this;
  73628. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73629. [], // samplers
  73630. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73631. this._highlightsPostProcess.onApply = function (effect) {
  73632. effect.setFloat('gain', _this._highlightsGain);
  73633. effect.setFloat('threshold', _this._highlightsThreshold);
  73634. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73635. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73636. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73637. };
  73638. };
  73639. // colors shifting and distortion
  73640. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73641. var _this = this;
  73642. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73643. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73644. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73645. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73646. this._depthOfFieldPostProcess.onApply = function (effect) {
  73647. effect.setTexture("depthSampler", _this._depthTexture);
  73648. effect.setTexture("grainSampler", _this._grainTexture);
  73649. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73650. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73651. effect.setFloat('grain_amount', _this._grainAmount);
  73652. effect.setBool('blur_noise', _this._blurNoise);
  73653. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73654. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73655. effect.setFloat('distortion', _this._distortion);
  73656. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73657. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73658. effect.setFloat('aperture', _this._dofAperture);
  73659. effect.setFloat('darken', _this._dofDarken);
  73660. effect.setFloat('edge_blur', _this._edgeBlur);
  73661. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73662. if (_this._scene.activeCamera) {
  73663. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73664. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73665. }
  73666. };
  73667. };
  73668. // creates a black and white random noise texture, 512x512
  73669. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73670. var size = 512;
  73671. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73672. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73673. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73674. var context = this._grainTexture.getContext();
  73675. var rand = function (min, max) {
  73676. return Math.random() * (max - min) + min;
  73677. };
  73678. var value;
  73679. for (var x = 0; x < size; x++) {
  73680. for (var y = 0; y < size; y++) {
  73681. value = Math.floor(rand(0.42, 0.58) * 255);
  73682. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73683. context.fillRect(x, y, 1, 1);
  73684. }
  73685. }
  73686. this._grainTexture.update(false);
  73687. };
  73688. return LensRenderingPipeline;
  73689. }(BABYLON.PostProcessRenderPipeline));
  73690. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73691. })(BABYLON || (BABYLON = {}));
  73692. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73693. var BABYLON;
  73694. (function (BABYLON) {
  73695. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73696. __extends(StandardRenderingPipeline, _super);
  73697. /**
  73698. * @constructor
  73699. * @param {string} name - The rendering pipeline name
  73700. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73701. * @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)
  73702. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73703. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73704. */
  73705. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73706. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73707. var _this = _super.call(this, scene.getEngine(), name) || this;
  73708. _this.downSampleX4PostProcess = null;
  73709. _this.brightPassPostProcess = null;
  73710. _this.blurHPostProcesses = [];
  73711. _this.blurVPostProcesses = [];
  73712. _this.textureAdderPostProcess = null;
  73713. _this.volumetricLightPostProcess = null;
  73714. _this.volumetricLightSmoothXPostProcess = null;
  73715. _this.volumetricLightSmoothYPostProcess = null;
  73716. _this.volumetricLightMergePostProces = null;
  73717. _this.volumetricLightFinalPostProcess = null;
  73718. _this.luminancePostProcess = null;
  73719. _this.luminanceDownSamplePostProcesses = [];
  73720. _this.hdrPostProcess = null;
  73721. _this.textureAdderFinalPostProcess = null;
  73722. _this.lensFlareFinalPostProcess = null;
  73723. _this.hdrFinalPostProcess = null;
  73724. _this.lensFlarePostProcess = null;
  73725. _this.lensFlareComposePostProcess = null;
  73726. _this.motionBlurPostProcess = null;
  73727. _this.depthOfFieldPostProcess = null;
  73728. // Values
  73729. _this.brightThreshold = 1.0;
  73730. _this.blurWidth = 512.0;
  73731. _this.horizontalBlur = false;
  73732. _this.exposure = 1.0;
  73733. _this.lensTexture = null;
  73734. _this.volumetricLightCoefficient = 0.2;
  73735. _this.volumetricLightPower = 4.0;
  73736. _this.volumetricLightBlurScale = 64.0;
  73737. _this.sourceLight = null;
  73738. _this.hdrMinimumLuminance = 1.0;
  73739. _this.hdrDecreaseRate = 0.5;
  73740. _this.hdrIncreaseRate = 0.5;
  73741. _this.lensColorTexture = null;
  73742. _this.lensFlareStrength = 20.0;
  73743. _this.lensFlareGhostDispersal = 1.4;
  73744. _this.lensFlareHaloWidth = 0.7;
  73745. _this.lensFlareDistortionStrength = 16.0;
  73746. _this.lensStarTexture = null;
  73747. _this.lensFlareDirtTexture = null;
  73748. _this.depthOfFieldDistance = 10.0;
  73749. _this.depthOfFieldBlurWidth = 64.0;
  73750. _this.motionStrength = 1.0;
  73751. // IAnimatable
  73752. _this.animations = [];
  73753. _this._currentDepthOfFieldSource = null;
  73754. _this._hdrCurrentLuminance = 1.0;
  73755. // Getters and setters
  73756. _this._bloomEnabled = true;
  73757. _this._depthOfFieldEnabled = false;
  73758. _this._vlsEnabled = false;
  73759. _this._lensFlareEnabled = false;
  73760. _this._hdrEnabled = false;
  73761. _this._motionBlurEnabled = false;
  73762. _this._motionBlurSamples = 64.0;
  73763. _this._volumetricLightStepsCount = 50.0;
  73764. _this._cameras = cameras || [];
  73765. // Initialize
  73766. _this._scene = scene;
  73767. _this._basePostProcess = originalPostProcess;
  73768. _this._ratio = ratio;
  73769. // Misc
  73770. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73771. // Finish
  73772. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73773. _this._buildPipeline();
  73774. return _this;
  73775. }
  73776. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73777. get: function () {
  73778. return this._bloomEnabled;
  73779. },
  73780. set: function (enabled) {
  73781. if (this._bloomEnabled === enabled) {
  73782. return;
  73783. }
  73784. this._bloomEnabled = enabled;
  73785. this._buildPipeline();
  73786. },
  73787. enumerable: true,
  73788. configurable: true
  73789. });
  73790. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73791. get: function () {
  73792. return this._depthOfFieldEnabled;
  73793. },
  73794. set: function (enabled) {
  73795. if (this._depthOfFieldEnabled === enabled) {
  73796. return;
  73797. }
  73798. this._depthOfFieldEnabled = enabled;
  73799. this._buildPipeline();
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73805. get: function () {
  73806. return this._lensFlareEnabled;
  73807. },
  73808. set: function (enabled) {
  73809. if (this._lensFlareEnabled === enabled) {
  73810. return;
  73811. }
  73812. this._lensFlareEnabled = enabled;
  73813. this._buildPipeline();
  73814. },
  73815. enumerable: true,
  73816. configurable: true
  73817. });
  73818. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73819. get: function () {
  73820. return this._hdrEnabled;
  73821. },
  73822. set: function (enabled) {
  73823. if (this._hdrEnabled === enabled) {
  73824. return;
  73825. }
  73826. this._hdrEnabled = enabled;
  73827. this._buildPipeline();
  73828. },
  73829. enumerable: true,
  73830. configurable: true
  73831. });
  73832. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73833. get: function () {
  73834. return this._vlsEnabled;
  73835. },
  73836. set: function (enabled) {
  73837. if (this._vlsEnabled === enabled) {
  73838. return;
  73839. }
  73840. if (enabled) {
  73841. var geometry = this._scene.enableGeometryBufferRenderer();
  73842. if (!geometry) {
  73843. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73844. return;
  73845. }
  73846. }
  73847. this._vlsEnabled = enabled;
  73848. this._buildPipeline();
  73849. },
  73850. enumerable: true,
  73851. configurable: true
  73852. });
  73853. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73854. get: function () {
  73855. return this._motionBlurEnabled;
  73856. },
  73857. set: function (enabled) {
  73858. if (this._motionBlurEnabled === enabled) {
  73859. return;
  73860. }
  73861. this._motionBlurEnabled = enabled;
  73862. this._buildPipeline();
  73863. },
  73864. enumerable: true,
  73865. configurable: true
  73866. });
  73867. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73868. get: function () {
  73869. return this._volumetricLightStepsCount;
  73870. },
  73871. set: function (count) {
  73872. if (this.volumetricLightPostProcess) {
  73873. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73874. }
  73875. this._volumetricLightStepsCount = count;
  73876. },
  73877. enumerable: true,
  73878. configurable: true
  73879. });
  73880. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73881. get: function () {
  73882. return this._motionBlurSamples;
  73883. },
  73884. set: function (samples) {
  73885. if (this.motionBlurPostProcess) {
  73886. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73887. }
  73888. this._motionBlurSamples = samples;
  73889. },
  73890. enumerable: true,
  73891. configurable: true
  73892. });
  73893. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73894. var _this = this;
  73895. var ratio = this._ratio;
  73896. var scene = this._scene;
  73897. this._disposePostProcesses();
  73898. this._reset();
  73899. // Create pass post-process
  73900. if (!this._basePostProcess) {
  73901. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73902. this.originalPostProcess.onApply = function (effect) {
  73903. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73904. };
  73905. }
  73906. else {
  73907. this.originalPostProcess = this._basePostProcess;
  73908. }
  73909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73910. this._currentDepthOfFieldSource = this.originalPostProcess;
  73911. if (this._bloomEnabled) {
  73912. // Create down sample X4 post-process
  73913. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73914. // Create bright pass post-process
  73915. this._createBrightPassPostProcess(scene, ratio / 2);
  73916. // Create gaussian blur post-processes (down sampling blurs)
  73917. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73918. // Create texture adder post-process
  73919. this._createTextureAdderPostProcess(scene, ratio);
  73920. // Create depth-of-field source post-process
  73921. 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);
  73922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73923. }
  73924. if (this._vlsEnabled) {
  73925. // Create volumetric light
  73926. this._createVolumetricLightPostProcess(scene, ratio);
  73927. // Create volumetric light final post-process
  73928. 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);
  73929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73930. }
  73931. if (this._lensFlareEnabled) {
  73932. // Create lens flare post-process
  73933. this._createLensFlarePostProcess(scene, ratio);
  73934. // Create depth-of-field source post-process post lens-flare and disable it now
  73935. 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);
  73936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73937. }
  73938. if (this._hdrEnabled) {
  73939. // Create luminance
  73940. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73941. // Create HDR
  73942. this._createHdrPostProcess(scene, ratio);
  73943. // Create depth-of-field source post-process post hdr and disable it now
  73944. 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);
  73945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73946. }
  73947. if (this._depthOfFieldEnabled) {
  73948. // Create gaussian blur used by depth-of-field
  73949. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73950. // Create depth-of-field post-process
  73951. this._createDepthOfFieldPostProcess(scene, ratio);
  73952. }
  73953. if (this._motionBlurEnabled) {
  73954. // Create motion blur post-process
  73955. this._createMotionBlurPostProcess(scene, ratio);
  73956. }
  73957. if (this._cameras !== null) {
  73958. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73959. }
  73960. };
  73961. // Down Sample X4 Post-Processs
  73962. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73963. var _this = this;
  73964. var downSampleX4Offsets = new Array(32);
  73965. 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);
  73966. this.downSampleX4PostProcess.onApply = function (effect) {
  73967. var id = 0;
  73968. var width = _this.downSampleX4PostProcess.width;
  73969. var height = _this.downSampleX4PostProcess.height;
  73970. for (var i = -2; i < 2; i++) {
  73971. for (var j = -2; j < 2; j++) {
  73972. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73973. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73974. id += 2;
  73975. }
  73976. }
  73977. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73978. };
  73979. // Add to pipeline
  73980. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73981. };
  73982. // Brightpass Post-Process
  73983. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73984. var _this = this;
  73985. var brightOffsets = new Array(8);
  73986. 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);
  73987. this.brightPassPostProcess.onApply = function (effect) {
  73988. var sU = (1.0 / _this.brightPassPostProcess.width);
  73989. var sV = (1.0 / _this.brightPassPostProcess.height);
  73990. brightOffsets[0] = -0.5 * sU;
  73991. brightOffsets[1] = 0.5 * sV;
  73992. brightOffsets[2] = 0.5 * sU;
  73993. brightOffsets[3] = 0.5 * sV;
  73994. brightOffsets[4] = -0.5 * sU;
  73995. brightOffsets[5] = -0.5 * sV;
  73996. brightOffsets[6] = 0.5 * sU;
  73997. brightOffsets[7] = -0.5 * sV;
  73998. effect.setArray2("dsOffsets", brightOffsets);
  73999. effect.setFloat("brightThreshold", _this.brightThreshold);
  74000. };
  74001. // Add to pipeline
  74002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74003. };
  74004. // Create blur H&V post-processes
  74005. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74006. var _this = this;
  74007. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74008. var engine = scene.getEngine();
  74009. 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);
  74010. 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);
  74011. blurX.onActivateObservable.add(function () {
  74012. var dw = blurX.width / engine.getRenderWidth();
  74013. blurX.kernel = _this[blurWidthKey] * dw;
  74014. });
  74015. blurY.onActivateObservable.add(function () {
  74016. var dw = blurY.height / engine.getRenderHeight();
  74017. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74018. });
  74019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74021. this.blurHPostProcesses.push(blurX);
  74022. this.blurVPostProcesses.push(blurY);
  74023. };
  74024. // Create texture adder post-process
  74025. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74026. var _this = this;
  74027. 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);
  74028. this.textureAdderPostProcess.onApply = function (effect) {
  74029. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74030. effect.setTexture("lensSampler", _this.lensTexture);
  74031. effect.setFloat("exposure", _this.exposure);
  74032. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74033. };
  74034. // Add to pipeline
  74035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74036. };
  74037. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74038. var _this = this;
  74039. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74040. geometryRenderer.enablePosition = true;
  74041. var geometry = geometryRenderer.getGBuffer();
  74042. // Base post-process
  74043. 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));
  74044. var depthValues = BABYLON.Vector2.Zero();
  74045. this.volumetricLightPostProcess.onApply = function (effect) {
  74046. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74047. var generator = _this.sourceLight.getShadowGenerator();
  74048. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74049. effect.setTexture("positionSampler", geometry.textures[2]);
  74050. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74051. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74052. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74053. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74054. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74055. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74056. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74057. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74058. effect.setVector2("depthValues", depthValues);
  74059. }
  74060. };
  74061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74062. // Smooth
  74063. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74064. // Merge
  74065. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74066. this.volumetricLightMergePostProces.onApply = function (effect) {
  74067. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74068. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74069. };
  74070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74071. };
  74072. // Create luminance
  74073. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74074. var _this = this;
  74075. // Create luminance
  74076. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74077. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74078. var offsets = [];
  74079. this.luminancePostProcess.onApply = function (effect) {
  74080. var sU = (1.0 / _this.luminancePostProcess.width);
  74081. var sV = (1.0 / _this.luminancePostProcess.height);
  74082. offsets[0] = -0.5 * sU;
  74083. offsets[1] = 0.5 * sV;
  74084. offsets[2] = 0.5 * sU;
  74085. offsets[3] = 0.5 * sV;
  74086. offsets[4] = -0.5 * sU;
  74087. offsets[5] = -0.5 * sV;
  74088. offsets[6] = 0.5 * sU;
  74089. offsets[7] = -0.5 * sV;
  74090. effect.setArray2("lumOffsets", offsets);
  74091. };
  74092. // Add to pipeline
  74093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74094. // Create down sample luminance
  74095. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74096. var size = Math.pow(3, i);
  74097. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74098. if (i === 0) {
  74099. defines += "#define FINAL_DOWN_SAMPLER";
  74100. }
  74101. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74102. this.luminanceDownSamplePostProcesses.push(postProcess);
  74103. }
  74104. // Create callbacks and add effects
  74105. var lastLuminance = this.luminancePostProcess;
  74106. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74107. var downSampleOffsets = new Array(18);
  74108. pp.onApply = function (effect) {
  74109. if (!lastLuminance) {
  74110. return;
  74111. }
  74112. var id = 0;
  74113. for (var x = -1; x < 2; x++) {
  74114. for (var y = -1; y < 2; y++) {
  74115. downSampleOffsets[id] = x / lastLuminance.width;
  74116. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74117. id += 2;
  74118. }
  74119. }
  74120. effect.setArray2("dsOffsets", downSampleOffsets);
  74121. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74122. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74123. lastLuminance = _this.luminancePostProcess;
  74124. }
  74125. else {
  74126. lastLuminance = pp;
  74127. }
  74128. };
  74129. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74130. pp.onAfterRender = function (effect) {
  74131. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74132. 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);
  74133. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74134. };
  74135. }
  74136. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74137. });
  74138. };
  74139. // Create HDR post-process
  74140. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74141. var _this = this;
  74142. 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);
  74143. var outputLiminance = 1;
  74144. var time = 0;
  74145. var lastTime = 0;
  74146. this.hdrPostProcess.onApply = function (effect) {
  74147. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74148. time += scene.getEngine().getDeltaTime();
  74149. if (outputLiminance < 0) {
  74150. outputLiminance = _this._hdrCurrentLuminance;
  74151. }
  74152. else {
  74153. var dt = (lastTime - time) / 1000.0;
  74154. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74155. outputLiminance += _this.hdrDecreaseRate * dt;
  74156. }
  74157. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74158. outputLiminance -= _this.hdrIncreaseRate * dt;
  74159. }
  74160. else {
  74161. outputLiminance = _this._hdrCurrentLuminance;
  74162. }
  74163. }
  74164. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74165. effect.setFloat("averageLuminance", outputLiminance);
  74166. lastTime = time;
  74167. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74168. };
  74169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74170. };
  74171. // Create lens flare post-process
  74172. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74173. var _this = this;
  74174. 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);
  74175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74176. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74177. 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);
  74178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74179. var resolution = new BABYLON.Vector2(0, 0);
  74180. // Lens flare
  74181. this.lensFlarePostProcess.onApply = function (effect) {
  74182. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74183. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74184. effect.setFloat("strength", _this.lensFlareStrength);
  74185. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74186. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74187. // Shift
  74188. resolution.x = _this.lensFlarePostProcess.width;
  74189. resolution.y = _this.lensFlarePostProcess.height;
  74190. effect.setVector2("resolution", resolution);
  74191. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74192. };
  74193. // Compose
  74194. 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);
  74195. 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);
  74196. this.lensFlareComposePostProcess.onApply = function (effect) {
  74197. if (!_this._scene.activeCamera) {
  74198. return;
  74199. }
  74200. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74201. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74202. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74203. // Lens start rotation matrix
  74204. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74205. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74206. 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));
  74207. camRot *= 4.0;
  74208. 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);
  74209. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74210. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74211. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74212. };
  74213. };
  74214. // Create depth-of-field post-process
  74215. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74216. var _this = this;
  74217. 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);
  74218. this.depthOfFieldPostProcess.onApply = function (effect) {
  74219. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74220. effect.setTexture("depthSampler", _this._getDepthTexture());
  74221. effect.setFloat("distance", _this.depthOfFieldDistance);
  74222. };
  74223. // Add to pipeline
  74224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74225. };
  74226. // Create motion blur post-process
  74227. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74228. var _this = this;
  74229. 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);
  74230. var motionScale = 0;
  74231. var prevViewProjection = BABYLON.Matrix.Identity();
  74232. var invViewProjection = BABYLON.Matrix.Identity();
  74233. var viewProjection = BABYLON.Matrix.Identity();
  74234. var screenSize = BABYLON.Vector2.Zero();
  74235. this.motionBlurPostProcess.onApply = function (effect) {
  74236. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74237. viewProjection.invertToRef(invViewProjection);
  74238. effect.setMatrix("inverseViewProjection", invViewProjection);
  74239. effect.setMatrix("prevViewProjection", prevViewProjection);
  74240. prevViewProjection = viewProjection;
  74241. screenSize.x = _this.motionBlurPostProcess.width;
  74242. screenSize.y = _this.motionBlurPostProcess.height;
  74243. effect.setVector2("screenSize", screenSize);
  74244. motionScale = scene.getEngine().getFps() / 60.0;
  74245. effect.setFloat("motionScale", motionScale);
  74246. effect.setFloat("motionStrength", _this.motionStrength);
  74247. effect.setTexture("depthSampler", _this._getDepthTexture());
  74248. };
  74249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74250. };
  74251. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74252. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74253. var renderer = this._scene.enableGeometryBufferRenderer();
  74254. return renderer.getGBuffer().textures[0];
  74255. }
  74256. return this._scene.enableDepthRenderer().getDepthMap();
  74257. };
  74258. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74259. for (var i = 0; i < this._cameras.length; i++) {
  74260. var camera = this._cameras[i];
  74261. if (this.originalPostProcess) {
  74262. this.originalPostProcess.dispose(camera);
  74263. }
  74264. if (this.downSampleX4PostProcess) {
  74265. this.downSampleX4PostProcess.dispose(camera);
  74266. }
  74267. if (this.brightPassPostProcess) {
  74268. this.brightPassPostProcess.dispose(camera);
  74269. }
  74270. if (this.textureAdderPostProcess) {
  74271. this.textureAdderPostProcess.dispose(camera);
  74272. }
  74273. if (this.textureAdderFinalPostProcess) {
  74274. this.textureAdderFinalPostProcess.dispose(camera);
  74275. }
  74276. if (this.volumetricLightPostProcess) {
  74277. this.volumetricLightPostProcess.dispose(camera);
  74278. }
  74279. if (this.volumetricLightSmoothXPostProcess) {
  74280. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74281. }
  74282. if (this.volumetricLightSmoothYPostProcess) {
  74283. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74284. }
  74285. if (this.volumetricLightMergePostProces) {
  74286. this.volumetricLightMergePostProces.dispose(camera);
  74287. }
  74288. if (this.volumetricLightFinalPostProcess) {
  74289. this.volumetricLightFinalPostProcess.dispose(camera);
  74290. }
  74291. if (this.lensFlarePostProcess) {
  74292. this.lensFlarePostProcess.dispose(camera);
  74293. }
  74294. if (this.lensFlareComposePostProcess) {
  74295. this.lensFlareComposePostProcess.dispose(camera);
  74296. }
  74297. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74298. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74299. }
  74300. if (this.luminancePostProcess) {
  74301. this.luminancePostProcess.dispose(camera);
  74302. }
  74303. if (this.hdrPostProcess) {
  74304. this.hdrPostProcess.dispose(camera);
  74305. }
  74306. if (this.hdrFinalPostProcess) {
  74307. this.hdrFinalPostProcess.dispose(camera);
  74308. }
  74309. if (this.depthOfFieldPostProcess) {
  74310. this.depthOfFieldPostProcess.dispose(camera);
  74311. }
  74312. if (this.motionBlurPostProcess) {
  74313. this.motionBlurPostProcess.dispose(camera);
  74314. }
  74315. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74316. this.blurHPostProcesses[j].dispose(camera);
  74317. }
  74318. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74319. this.blurVPostProcesses[j].dispose(camera);
  74320. }
  74321. }
  74322. this.originalPostProcess = null;
  74323. this.downSampleX4PostProcess = null;
  74324. this.brightPassPostProcess = null;
  74325. this.textureAdderPostProcess = null;
  74326. this.textureAdderFinalPostProcess = null;
  74327. this.volumetricLightPostProcess = null;
  74328. this.volumetricLightSmoothXPostProcess = null;
  74329. this.volumetricLightSmoothYPostProcess = null;
  74330. this.volumetricLightMergePostProces = null;
  74331. this.volumetricLightFinalPostProcess = null;
  74332. this.lensFlarePostProcess = null;
  74333. this.lensFlareComposePostProcess = null;
  74334. this.luminancePostProcess = null;
  74335. this.hdrPostProcess = null;
  74336. this.hdrFinalPostProcess = null;
  74337. this.depthOfFieldPostProcess = null;
  74338. this.motionBlurPostProcess = null;
  74339. this.luminanceDownSamplePostProcesses = [];
  74340. this.blurHPostProcesses = [];
  74341. this.blurVPostProcesses = [];
  74342. };
  74343. /**
  74344. * Dispose of the pipeline and stop all post processes
  74345. */
  74346. StandardRenderingPipeline.prototype.dispose = function () {
  74347. this._disposePostProcesses();
  74348. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74349. _super.prototype.dispose.call(this);
  74350. };
  74351. /**
  74352. * Serialize the rendering pipeline (Used when exporting)
  74353. * @returns the serialized object
  74354. */
  74355. StandardRenderingPipeline.prototype.serialize = function () {
  74356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74357. if (this.sourceLight) {
  74358. serializationObject.sourceLightId = this.sourceLight.id;
  74359. }
  74360. serializationObject.customType = "StandardRenderingPipeline";
  74361. return serializationObject;
  74362. };
  74363. /**
  74364. * Parse the serialized pipeline
  74365. * @param source Source pipeline.
  74366. * @param scene The scene to load the pipeline to.
  74367. * @param rootUrl The URL of the serialized pipeline.
  74368. * @returns An instantiated pipeline from the serialized object.
  74369. */
  74370. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74371. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74372. if (source.sourceLightId) {
  74373. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74374. }
  74375. return p;
  74376. };
  74377. // Luminance steps
  74378. StandardRenderingPipeline.LuminanceSteps = 6;
  74379. __decorate([
  74380. BABYLON.serialize()
  74381. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74382. __decorate([
  74383. BABYLON.serialize()
  74384. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74385. __decorate([
  74386. BABYLON.serialize()
  74387. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74388. __decorate([
  74389. BABYLON.serialize()
  74390. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74391. __decorate([
  74392. BABYLON.serializeAsTexture("lensTexture")
  74393. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74394. __decorate([
  74395. BABYLON.serialize()
  74396. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74397. __decorate([
  74398. BABYLON.serialize()
  74399. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74400. __decorate([
  74401. BABYLON.serialize()
  74402. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74403. __decorate([
  74404. BABYLON.serialize()
  74405. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74406. __decorate([
  74407. BABYLON.serialize()
  74408. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74409. __decorate([
  74410. BABYLON.serialize()
  74411. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74412. __decorate([
  74413. BABYLON.serializeAsTexture("lensColorTexture")
  74414. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74415. __decorate([
  74416. BABYLON.serialize()
  74417. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74418. __decorate([
  74419. BABYLON.serialize()
  74420. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74421. __decorate([
  74422. BABYLON.serialize()
  74423. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74424. __decorate([
  74425. BABYLON.serialize()
  74426. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74427. __decorate([
  74428. BABYLON.serializeAsTexture("lensStarTexture")
  74429. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74430. __decorate([
  74431. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74432. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74433. __decorate([
  74434. BABYLON.serialize()
  74435. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74436. __decorate([
  74437. BABYLON.serialize()
  74438. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74439. __decorate([
  74440. BABYLON.serialize()
  74441. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74442. __decorate([
  74443. BABYLON.serialize()
  74444. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74445. __decorate([
  74446. BABYLON.serialize()
  74447. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74448. __decorate([
  74449. BABYLON.serialize()
  74450. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74451. __decorate([
  74452. BABYLON.serialize()
  74453. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74454. __decorate([
  74455. BABYLON.serialize()
  74456. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74457. __decorate([
  74458. BABYLON.serialize()
  74459. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74460. __decorate([
  74461. BABYLON.serialize()
  74462. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74463. __decorate([
  74464. BABYLON.serialize()
  74465. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74466. __decorate([
  74467. BABYLON.serialize()
  74468. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74469. return StandardRenderingPipeline;
  74470. }(BABYLON.PostProcessRenderPipeline));
  74471. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74472. })(BABYLON || (BABYLON = {}));
  74473. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74474. var BABYLON;
  74475. (function (BABYLON) {
  74476. var FxaaPostProcess = /** @class */ (function (_super) {
  74477. __extends(FxaaPostProcess, _super);
  74478. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74479. if (camera === void 0) { camera = null; }
  74480. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74481. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74482. var defines = _this._getDefines();
  74483. _this.updateEffect(defines);
  74484. _this.onApplyObservable.add(function (effect) {
  74485. var texelSize = _this.texelSize;
  74486. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74487. });
  74488. return _this;
  74489. }
  74490. FxaaPostProcess.prototype._getDefines = function () {
  74491. var engine = this.getEngine();
  74492. if (!engine) {
  74493. return null;
  74494. }
  74495. var glInfo = engine.getGlInfo();
  74496. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74497. return "#define MALI 1\n";
  74498. }
  74499. return null;
  74500. };
  74501. return FxaaPostProcess;
  74502. }(BABYLON.PostProcess));
  74503. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74504. })(BABYLON || (BABYLON = {}));
  74505. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74506. var BABYLON;
  74507. (function (BABYLON) {
  74508. /**
  74509. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74510. */
  74511. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74512. __extends(ChromaticAberrationPostProcess, _super);
  74513. /**
  74514. * Creates a new instance ChromaticAberrationPostProcess
  74515. * @param name The name of the effect.
  74516. * @param screenWidth The width of the screen to apply the effect on.
  74517. * @param screenHeight The height of the screen to apply the effect on.
  74518. * @param options The required width/height ratio to downsize to before computing the render pass.
  74519. * @param camera The camera to apply the render pass to.
  74520. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74521. * @param engine The engine which the post process will be applied. (default: current engine)
  74522. * @param reusable If the post process can be reused on the same frame. (default: false)
  74523. * @param textureType Type of textures used when performing the post process. (default: 0)
  74524. * @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)
  74525. */
  74526. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74527. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74528. if (blockCompilation === void 0) { blockCompilation = false; }
  74529. 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;
  74530. /**
  74531. * The amount of seperation of rgb channels (default: 30)
  74532. */
  74533. _this.aberrationAmount = 30;
  74534. /**
  74535. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74536. */
  74537. _this.radialIntensity = 0;
  74538. /**
  74539. * 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))
  74540. */
  74541. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74542. /**
  74543. * 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))
  74544. */
  74545. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74546. _this.onApplyObservable.add(function (effect) {
  74547. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74548. effect.setFloat('screen_width', screenWidth);
  74549. effect.setFloat('screen_height', screenHeight);
  74550. effect.setFloat('radialIntensity', _this.radialIntensity);
  74551. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74552. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74553. });
  74554. return _this;
  74555. }
  74556. return ChromaticAberrationPostProcess;
  74557. }(BABYLON.PostProcess));
  74558. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74559. })(BABYLON || (BABYLON = {}));
  74560. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74561. var BABYLON;
  74562. (function (BABYLON) {
  74563. /**
  74564. * The GrainPostProcess adds noise to the image at mid luminance levels
  74565. */
  74566. var GrainPostProcess = /** @class */ (function (_super) {
  74567. __extends(GrainPostProcess, _super);
  74568. /**
  74569. * Creates a new instance of @see GrainPostProcess
  74570. * @param name The name of the effect.
  74571. * @param options The required width/height ratio to downsize to before computing the render pass.
  74572. * @param camera The camera to apply the render pass to.
  74573. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74574. * @param engine The engine which the post process will be applied. (default: current engine)
  74575. * @param reusable If the post process can be reused on the same frame. (default: false)
  74576. * @param textureType Type of textures used when performing the post process. (default: 0)
  74577. * @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)
  74578. */
  74579. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74581. if (blockCompilation === void 0) { blockCompilation = false; }
  74582. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74583. /**
  74584. * The intensity of the grain added (default: 30)
  74585. */
  74586. _this.intensity = 30;
  74587. /**
  74588. * If the grain should be randomized on every frame
  74589. */
  74590. _this.animated = false;
  74591. _this.onApplyObservable.add(function (effect) {
  74592. effect.setFloat('intensity', _this.intensity);
  74593. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74594. });
  74595. return _this;
  74596. }
  74597. return GrainPostProcess;
  74598. }(BABYLON.PostProcess));
  74599. BABYLON.GrainPostProcess = GrainPostProcess;
  74600. })(BABYLON || (BABYLON = {}));
  74601. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74602. var BABYLON;
  74603. (function (BABYLON) {
  74604. /**
  74605. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74606. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74607. */
  74608. var SharpenPostProcess = /** @class */ (function (_super) {
  74609. __extends(SharpenPostProcess, _super);
  74610. /**
  74611. * Creates a new instance ConvolutionPostProcess
  74612. * @param name The name of the effect.
  74613. * @param options The required width/height ratio to downsize to before computing the render pass.
  74614. * @param camera The camera to apply the render pass to.
  74615. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74616. * @param engine The engine which the post process will be applied. (default: current engine)
  74617. * @param reusable If the post process can be reused on the same frame. (default: false)
  74618. * @param textureType Type of textures used when performing the post process. (default: 0)
  74619. * @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)
  74620. */
  74621. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74622. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74623. if (blockCompilation === void 0) { blockCompilation = false; }
  74624. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74625. /**
  74626. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74627. */
  74628. _this.colorAmount = 1.0;
  74629. /**
  74630. * How much sharpness should be applied (default: 0.3)
  74631. */
  74632. _this.edgeAmount = 0.3;
  74633. _this.onApply = function (effect) {
  74634. effect.setFloat2("screenSize", _this.width, _this.height);
  74635. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74636. };
  74637. return _this;
  74638. }
  74639. return SharpenPostProcess;
  74640. }(BABYLON.PostProcess));
  74641. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74642. })(BABYLON || (BABYLON = {}));
  74643. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74644. var BABYLON;
  74645. (function (BABYLON) {
  74646. /**
  74647. * The Blur Post Process which blurs an image based on a kernel and direction.
  74648. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74649. */
  74650. var BlurPostProcess = /** @class */ (function (_super) {
  74651. __extends(BlurPostProcess, _super);
  74652. /**
  74653. * Creates a new instance BlurPostProcess
  74654. * @param name The name of the effect.
  74655. * @param direction The direction in which to blur the image.
  74656. * @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.
  74657. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74658. * @param camera The camera to apply the render pass to.
  74659. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74660. * @param engine The engine which the post process will be applied. (default: current engine)
  74661. * @param reusable If the post process can be reused on the same frame. (default: false)
  74662. * @param textureType Type of textures used when performing the post process. (default: 0)
  74663. * @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)
  74664. */
  74665. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74667. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74668. if (defines === void 0) { defines = ""; }
  74669. if (blockCompilation === void 0) { blockCompilation = false; }
  74670. 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;
  74671. _this.direction = direction;
  74672. _this.blockCompilation = blockCompilation;
  74673. _this._packedFloat = false;
  74674. _this._staticDefines = "";
  74675. _this._staticDefines = defines;
  74676. _this.onApplyObservable.add(function (effect) {
  74677. if (_this._outputTexture) {
  74678. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74679. }
  74680. else {
  74681. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74682. }
  74683. });
  74684. _this.kernel = kernel;
  74685. return _this;
  74686. }
  74687. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74688. /**
  74689. * Gets the length in pixels of the blur sample region
  74690. */
  74691. get: function () {
  74692. return this._idealKernel;
  74693. },
  74694. /**
  74695. * Sets the length in pixels of the blur sample region
  74696. */
  74697. set: function (v) {
  74698. if (this._idealKernel === v) {
  74699. return;
  74700. }
  74701. v = Math.max(v, 1);
  74702. this._idealKernel = v;
  74703. this._kernel = this._nearestBestKernel(v);
  74704. if (!this.blockCompilation) {
  74705. this._updateParameters();
  74706. }
  74707. },
  74708. enumerable: true,
  74709. configurable: true
  74710. });
  74711. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74712. /**
  74713. * Gets wether or not the blur is unpacking/repacking floats
  74714. */
  74715. get: function () {
  74716. return this._packedFloat;
  74717. },
  74718. /**
  74719. * Sets wether or not the blur needs to unpack/repack floats
  74720. */
  74721. set: function (v) {
  74722. if (this._packedFloat === v) {
  74723. return;
  74724. }
  74725. this._packedFloat = v;
  74726. if (!this.blockCompilation) {
  74727. this._updateParameters();
  74728. }
  74729. },
  74730. enumerable: true,
  74731. configurable: true
  74732. });
  74733. /**
  74734. * Updates the effect with the current post process compile time values and recompiles the shader.
  74735. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74736. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74737. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74738. * @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
  74739. * @param onCompiled Called when the shader has been compiled.
  74740. * @param onError Called if there is an error when compiling a shader.
  74741. */
  74742. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74743. if (defines === void 0) { defines = null; }
  74744. if (uniforms === void 0) { uniforms = null; }
  74745. if (samplers === void 0) { samplers = null; }
  74746. this._updateParameters(onCompiled, onError);
  74747. };
  74748. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74749. // Generate sampling offsets and weights
  74750. var N = this._kernel;
  74751. var centerIndex = (N - 1) / 2;
  74752. // Generate Gaussian sampling weights over kernel
  74753. var offsets = [];
  74754. var weights = [];
  74755. var totalWeight = 0;
  74756. for (var i = 0; i < N; i++) {
  74757. var u = i / (N - 1);
  74758. var w = this._gaussianWeight(u * 2.0 - 1);
  74759. offsets[i] = (i - centerIndex);
  74760. weights[i] = w;
  74761. totalWeight += w;
  74762. }
  74763. // Normalize weights
  74764. for (var i = 0; i < weights.length; i++) {
  74765. weights[i] /= totalWeight;
  74766. }
  74767. // Optimize: combine samples to take advantage of hardware linear sampling
  74768. // Walk from left to center, combining pairs (symmetrically)
  74769. var linearSamplingWeights = [];
  74770. var linearSamplingOffsets = [];
  74771. var linearSamplingMap = [];
  74772. for (var i = 0; i <= centerIndex; i += 2) {
  74773. var j = Math.min(i + 1, Math.floor(centerIndex));
  74774. var singleCenterSample = i === j;
  74775. if (singleCenterSample) {
  74776. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74777. }
  74778. else {
  74779. var sharedCell = j === centerIndex;
  74780. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74781. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74782. if (offsetLinear === 0) {
  74783. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74784. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74785. }
  74786. else {
  74787. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74788. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74789. }
  74790. }
  74791. }
  74792. for (var i = 0; i < linearSamplingMap.length; i++) {
  74793. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74794. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74795. }
  74796. // Replace with optimized
  74797. offsets = linearSamplingOffsets;
  74798. weights = linearSamplingWeights;
  74799. // Generate shaders
  74800. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74801. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74802. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74803. var defines = "";
  74804. defines += this._staticDefines;
  74805. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74806. if (this._staticDefines.indexOf("DOF") != -1) {
  74807. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74808. varyingCount--;
  74809. }
  74810. for (var i = 0; i < varyingCount; i++) {
  74811. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74812. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74813. }
  74814. var depCount = 0;
  74815. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74816. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74817. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74818. depCount++;
  74819. }
  74820. if (this.packedFloat) {
  74821. defines += "#define PACKEDFLOAT 1";
  74822. }
  74823. this.blockCompilation = false;
  74824. _super.prototype.updateEffect.call(this, defines, null, null, {
  74825. varyingCount: varyingCount,
  74826. depCount: depCount
  74827. }, onCompiled, onError);
  74828. };
  74829. /**
  74830. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74831. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74832. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74833. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74834. * The gaps between physical kernels are compensated for in the weighting of the samples
  74835. * @param idealKernel Ideal blur kernel.
  74836. * @return Nearest best kernel.
  74837. */
  74838. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74839. var v = Math.round(idealKernel);
  74840. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74841. var k = _a[_i];
  74842. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74843. return Math.max(k, 3);
  74844. }
  74845. }
  74846. return Math.max(v, 3);
  74847. };
  74848. /**
  74849. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74850. * @param x The point on the Gaussian distribution to sample.
  74851. * @return the value of the Gaussian function at x.
  74852. */
  74853. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74854. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74855. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74856. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74857. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74858. // truncated at around 1.3% of peak strength.
  74859. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74860. var sigma = (1 / 3);
  74861. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74862. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74863. var weight = (1.0 / denominator) * Math.exp(exponent);
  74864. return weight;
  74865. };
  74866. /**
  74867. * Generates a string that can be used as a floating point number in GLSL.
  74868. * @param x Value to print.
  74869. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74870. * @return GLSL float string.
  74871. */
  74872. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74873. if (decimalFigures === void 0) { decimalFigures = 8; }
  74874. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74875. };
  74876. return BlurPostProcess;
  74877. }(BABYLON.PostProcess));
  74878. BABYLON.BlurPostProcess = BlurPostProcess;
  74879. })(BABYLON || (BABYLON = {}));
  74880. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74881. var BABYLON;
  74882. (function (BABYLON) {
  74883. /**
  74884. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74885. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74886. * based on samples that have a large difference in distance than the center pixel.
  74887. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74888. */
  74889. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74890. __extends(DepthOfFieldBlurPostProcess, _super);
  74891. /**
  74892. * Creates a new instance CircleOfConfusionPostProcess
  74893. * @param name The name of the effect.
  74894. * @param scene The scene the effect belongs to.
  74895. * @param direction The direction the blur should be applied.
  74896. * @param kernel The size of the kernel used to blur.
  74897. * @param options The required width/height ratio to downsize to before computing the render pass.
  74898. * @param camera The camera to apply the render pass to.
  74899. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74900. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74901. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74902. * @param engine The engine which the post process will be applied. (default: current engine)
  74903. * @param reusable If the post process can be reused on the same frame. (default: false)
  74904. * @param textureType Type of textures used when performing the post process. (default: 0)
  74905. * @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)
  74906. */
  74907. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74908. if (imageToBlur === void 0) { imageToBlur = null; }
  74909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74910. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74911. if (blockCompilation === void 0) { blockCompilation = false; }
  74912. 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;
  74913. _this.direction = direction;
  74914. _this.onApplyObservable.add(function (effect) {
  74915. if (imageToBlur != null) {
  74916. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74917. }
  74918. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74919. if (scene.activeCamera) {
  74920. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74921. }
  74922. });
  74923. return _this;
  74924. }
  74925. return DepthOfFieldBlurPostProcess;
  74926. }(BABYLON.BlurPostProcess));
  74927. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74928. })(BABYLON || (BABYLON = {}));
  74929. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74930. var BABYLON;
  74931. (function (BABYLON) {
  74932. /**
  74933. * Options to be set when merging outputs from the default pipeline.
  74934. */
  74935. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74936. function DepthOfFieldMergePostProcessOptions() {
  74937. }
  74938. return DepthOfFieldMergePostProcessOptions;
  74939. }());
  74940. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74941. /**
  74942. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74943. */
  74944. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74945. __extends(DepthOfFieldMergePostProcess, _super);
  74946. /**
  74947. * Creates a new instance of DepthOfFieldMergePostProcess
  74948. * @param name The name of the effect.
  74949. * @param originalFromInput Post process which's input will be used for the merge.
  74950. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74951. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74952. * @param options The required width/height ratio to downsize to before computing the render pass.
  74953. * @param camera The camera to apply the render pass to.
  74954. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74955. * @param engine The engine which the post process will be applied. (default: current engine)
  74956. * @param reusable If the post process can be reused on the same frame. (default: false)
  74957. * @param textureType Type of textures used when performing the post process. (default: 0)
  74958. * @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)
  74959. */
  74960. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74961. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74962. if (blockCompilation === void 0) { blockCompilation = false; }
  74963. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74964. _this.blurSteps = blurSteps;
  74965. _this.onApplyObservable.add(function (effect) {
  74966. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74967. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74968. blurSteps.forEach(function (step, index) {
  74969. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74970. });
  74971. });
  74972. if (!blockCompilation) {
  74973. _this.updateEffect();
  74974. }
  74975. return _this;
  74976. }
  74977. /**
  74978. * Updates the effect with the current post process compile time values and recompiles the shader.
  74979. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74980. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74981. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74982. * @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
  74983. * @param onCompiled Called when the shader has been compiled.
  74984. * @param onError Called if there is an error when compiling a shader.
  74985. */
  74986. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74987. if (defines === void 0) { defines = null; }
  74988. if (uniforms === void 0) { uniforms = null; }
  74989. if (samplers === void 0) { samplers = null; }
  74990. if (!defines) {
  74991. defines = "";
  74992. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74993. }
  74994. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74995. };
  74996. return DepthOfFieldMergePostProcess;
  74997. }(BABYLON.PostProcess));
  74998. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74999. })(BABYLON || (BABYLON = {}));
  75000. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75001. var BABYLON;
  75002. (function (BABYLON) {
  75003. /**
  75004. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75005. */
  75006. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75007. __extends(CircleOfConfusionPostProcess, _super);
  75008. /**
  75009. * Creates a new instance CircleOfConfusionPostProcess
  75010. * @param name The name of the effect.
  75011. * @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.
  75012. * @param options The required width/height ratio to downsize to before computing the render pass.
  75013. * @param camera The camera to apply the render pass to.
  75014. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75015. * @param engine The engine which the post process will be applied. (default: current engine)
  75016. * @param reusable If the post process can be reused on the same frame. (default: false)
  75017. * @param textureType Type of textures used when performing the post process. (default: 0)
  75018. * @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)
  75019. */
  75020. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75021. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75022. if (blockCompilation === void 0) { blockCompilation = false; }
  75023. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75024. /**
  75025. * 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.
  75026. */
  75027. _this.lensSize = 50;
  75028. /**
  75029. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75030. */
  75031. _this.fStop = 1.4;
  75032. /**
  75033. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75034. */
  75035. _this.focusDistance = 2000;
  75036. /**
  75037. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75038. */
  75039. _this.focalLength = 50;
  75040. _this._depthTexture = null;
  75041. _this._depthTexture = depthTexture;
  75042. _this.onApplyObservable.add(function (effect) {
  75043. if (!_this._depthTexture) {
  75044. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75045. return;
  75046. }
  75047. effect.setTexture("depthSampler", _this._depthTexture);
  75048. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75049. var aperture = _this.lensSize / _this.fStop;
  75050. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75051. effect.setFloat('focusDistance', _this.focusDistance);
  75052. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75053. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75054. });
  75055. return _this;
  75056. }
  75057. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75058. /**
  75059. * 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.
  75060. */
  75061. set: function (value) {
  75062. this._depthTexture = value;
  75063. },
  75064. enumerable: true,
  75065. configurable: true
  75066. });
  75067. return CircleOfConfusionPostProcess;
  75068. }(BABYLON.PostProcess));
  75069. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75070. })(BABYLON || (BABYLON = {}));
  75071. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75072. var BABYLON;
  75073. (function (BABYLON) {
  75074. /**
  75075. * Specifies the level of max blur that should be applied when using the depth of field effect
  75076. */
  75077. var DepthOfFieldEffectBlurLevel;
  75078. (function (DepthOfFieldEffectBlurLevel) {
  75079. /**
  75080. * Subtle blur
  75081. */
  75082. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75083. /**
  75084. * Medium blur
  75085. */
  75086. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75087. /**
  75088. * Large blur
  75089. */
  75090. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75091. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75092. ;
  75093. /**
  75094. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75095. */
  75096. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75097. __extends(DepthOfFieldEffect, _super);
  75098. /**
  75099. * Creates a new instance DepthOfFieldEffect
  75100. * @param scene The scene the effect belongs to.
  75101. * @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.
  75102. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75103. * @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)
  75104. */
  75105. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75106. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75107. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75108. if (blockCompilation === void 0) { blockCompilation = false; }
  75109. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75110. return _this._effects;
  75111. }, true) || this;
  75112. /**
  75113. * Internal post processes in depth of field effect
  75114. */
  75115. _this._effects = [];
  75116. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75117. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75118. // 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)
  75119. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75120. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75121. _this._depthOfFieldBlurY = [];
  75122. _this._depthOfFieldBlurX = [];
  75123. var blurCount = 1;
  75124. var kernelSize = 15;
  75125. switch (blurLevel) {
  75126. case DepthOfFieldEffectBlurLevel.High: {
  75127. blurCount = 3;
  75128. kernelSize = 51;
  75129. break;
  75130. }
  75131. case DepthOfFieldEffectBlurLevel.Medium: {
  75132. blurCount = 2;
  75133. kernelSize = 31;
  75134. break;
  75135. }
  75136. default: {
  75137. kernelSize = 15;
  75138. blurCount = 1;
  75139. break;
  75140. }
  75141. }
  75142. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75143. var ratio = 1.0;
  75144. for (var i = 0; i < blurCount; i++) {
  75145. 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);
  75146. blurY.autoClear = false;
  75147. ratio = 0.75 / Math.pow(2, i);
  75148. 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);
  75149. blurX.autoClear = false;
  75150. _this._depthOfFieldBlurY.push(blurY);
  75151. _this._depthOfFieldBlurX.push(blurX);
  75152. }
  75153. // Set all post processes on the effect.
  75154. _this._effects = [_this._circleOfConfusion];
  75155. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75156. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75157. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75158. }
  75159. // Merge blurred images with original image based on circleOfConfusion
  75160. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75161. _this._dofMerge.autoClear = false;
  75162. _this._effects.push(_this._dofMerge);
  75163. return _this;
  75164. }
  75165. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75166. get: function () {
  75167. return this._circleOfConfusion.focalLength;
  75168. },
  75169. /**
  75170. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75171. */
  75172. set: function (value) {
  75173. this._circleOfConfusion.focalLength = value;
  75174. },
  75175. enumerable: true,
  75176. configurable: true
  75177. });
  75178. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75179. get: function () {
  75180. return this._circleOfConfusion.fStop;
  75181. },
  75182. /**
  75183. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75184. */
  75185. set: function (value) {
  75186. this._circleOfConfusion.fStop = value;
  75187. },
  75188. enumerable: true,
  75189. configurable: true
  75190. });
  75191. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75192. get: function () {
  75193. return this._circleOfConfusion.focusDistance;
  75194. },
  75195. /**
  75196. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75197. */
  75198. set: function (value) {
  75199. this._circleOfConfusion.focusDistance = value;
  75200. },
  75201. enumerable: true,
  75202. configurable: true
  75203. });
  75204. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75205. get: function () {
  75206. return this._circleOfConfusion.lensSize;
  75207. },
  75208. /**
  75209. * 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.
  75210. */
  75211. set: function (value) {
  75212. this._circleOfConfusion.lensSize = value;
  75213. },
  75214. enumerable: true,
  75215. configurable: true
  75216. });
  75217. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75218. /**
  75219. * 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.
  75220. */
  75221. set: function (value) {
  75222. this._circleOfConfusion.depthTexture = value;
  75223. },
  75224. enumerable: true,
  75225. configurable: true
  75226. });
  75227. /**
  75228. * Disposes each of the internal effects for a given camera.
  75229. * @param camera The camera to dispose the effect on.
  75230. */
  75231. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75232. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75233. this._effects[effectIndex].dispose(camera);
  75234. }
  75235. };
  75236. /**
  75237. * Internal
  75238. */
  75239. DepthOfFieldEffect.prototype._updateEffects = function () {
  75240. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75241. this._effects[effectIndex].updateEffect();
  75242. }
  75243. };
  75244. /**
  75245. * Internal
  75246. * @returns if all the contained post processes are ready.
  75247. */
  75248. DepthOfFieldEffect.prototype._isReady = function () {
  75249. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75250. if (!this._effects[effectIndex].isReady()) {
  75251. return false;
  75252. }
  75253. }
  75254. return true;
  75255. };
  75256. return DepthOfFieldEffect;
  75257. }(BABYLON.PostProcessRenderEffect));
  75258. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75259. })(BABYLON || (BABYLON = {}));
  75260. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75261. var BABYLON;
  75262. (function (BABYLON) {
  75263. /**
  75264. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75265. */
  75266. var BloomMergePostProcess = /** @class */ (function (_super) {
  75267. __extends(BloomMergePostProcess, _super);
  75268. /**
  75269. * Creates a new instance of @see BloomMergePostProcess
  75270. * @param name The name of the effect.
  75271. * @param originalFromInput Post process which's input will be used for the merge.
  75272. * @param blurred Blurred highlights post process which's output will be used.
  75273. * @param weight Weight of the bloom to be added to the original input.
  75274. * @param options The required width/height ratio to downsize to before computing the render pass.
  75275. * @param camera The camera to apply the render pass to.
  75276. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75277. * @param engine The engine which the post process will be applied. (default: current engine)
  75278. * @param reusable If the post process can be reused on the same frame. (default: false)
  75279. * @param textureType Type of textures used when performing the post process. (default: 0)
  75280. * @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)
  75281. */
  75282. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75283. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75284. if (blockCompilation === void 0) { blockCompilation = false; }
  75285. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75286. _this.weight = weight;
  75287. _this.onApplyObservable.add(function (effect) {
  75288. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75289. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75290. effect.setFloat("bloomWeight", _this.weight);
  75291. });
  75292. if (!blockCompilation) {
  75293. _this.updateEffect();
  75294. }
  75295. return _this;
  75296. }
  75297. return BloomMergePostProcess;
  75298. }(BABYLON.PostProcess));
  75299. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75300. })(BABYLON || (BABYLON = {}));
  75301. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75302. var BABYLON;
  75303. (function (BABYLON) {
  75304. /**
  75305. * 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.
  75306. */
  75307. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75308. __extends(ExtractHighlightsPostProcess, _super);
  75309. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75310. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75311. if (blockCompilation === void 0) { blockCompilation = false; }
  75312. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75313. /**
  75314. * The luminance threshold, pixels below this value will be set to black.
  75315. */
  75316. _this.threshold = 0.9;
  75317. /**
  75318. * Internal
  75319. */
  75320. _this._exposure = 1;
  75321. /**
  75322. * Post process which has the input texture to be used when performing highlight extraction
  75323. */
  75324. _this._inputPostProcess = null;
  75325. _this.onApplyObservable.add(function (effect) {
  75326. if (_this._inputPostProcess) {
  75327. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75328. }
  75329. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75330. effect.setFloat('exposure', _this._exposure);
  75331. });
  75332. return _this;
  75333. }
  75334. return ExtractHighlightsPostProcess;
  75335. }(BABYLON.PostProcess));
  75336. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75337. })(BABYLON || (BABYLON = {}));
  75338. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75339. var BABYLON;
  75340. (function (BABYLON) {
  75341. /**
  75342. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75343. */
  75344. var BloomEffect = /** @class */ (function (_super) {
  75345. __extends(BloomEffect, _super);
  75346. /**
  75347. * Creates a new instance of @see BloomEffect
  75348. * @param scene The scene the effect belongs to.
  75349. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75350. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75351. * @param bloomWeight The the strength of bloom.
  75352. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75353. * @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)
  75354. */
  75355. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75356. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75357. if (blockCompilation === void 0) { blockCompilation = false; }
  75358. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75359. return _this._effects;
  75360. }, true) || this;
  75361. _this.bloomScale = bloomScale;
  75362. /**
  75363. * Internal
  75364. */
  75365. _this._effects = [];
  75366. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75367. _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);
  75368. _this._blurX.alwaysForcePOT = true;
  75369. _this._blurX.autoClear = false;
  75370. _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);
  75371. _this._blurY.alwaysForcePOT = true;
  75372. _this._blurY.autoClear = false;
  75373. _this.kernel = bloomKernel;
  75374. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75375. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75376. _this._merge.autoClear = false;
  75377. _this._effects.push(_this._merge);
  75378. return _this;
  75379. }
  75380. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75381. /**
  75382. * The luminance threshold to find bright areas of the image to bloom.
  75383. */
  75384. get: function () {
  75385. return this._downscale.threshold;
  75386. },
  75387. set: function (value) {
  75388. this._downscale.threshold = value;
  75389. },
  75390. enumerable: true,
  75391. configurable: true
  75392. });
  75393. Object.defineProperty(BloomEffect.prototype, "weight", {
  75394. /**
  75395. * The strength of the bloom.
  75396. */
  75397. get: function () {
  75398. return this._merge.weight;
  75399. },
  75400. set: function (value) {
  75401. this._merge.weight = value;
  75402. },
  75403. enumerable: true,
  75404. configurable: true
  75405. });
  75406. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75407. /**
  75408. * Specifies the size of the bloom blur kernel, relative to the final output size
  75409. */
  75410. get: function () {
  75411. return this._blurX.kernel / this.bloomScale;
  75412. },
  75413. set: function (value) {
  75414. this._blurX.kernel = value * this.bloomScale;
  75415. this._blurY.kernel = value * this.bloomScale;
  75416. },
  75417. enumerable: true,
  75418. configurable: true
  75419. });
  75420. /**
  75421. * Disposes each of the internal effects for a given camera.
  75422. * @param camera The camera to dispose the effect on.
  75423. */
  75424. BloomEffect.prototype.disposeEffects = function (camera) {
  75425. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75426. this._effects[effectIndex].dispose(camera);
  75427. }
  75428. };
  75429. /**
  75430. * Internal
  75431. */
  75432. BloomEffect.prototype._updateEffects = function () {
  75433. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75434. this._effects[effectIndex].updateEffect();
  75435. }
  75436. };
  75437. /**
  75438. * Internal
  75439. * @returns if all the contained post processes are ready.
  75440. */
  75441. BloomEffect.prototype._isReady = function () {
  75442. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75443. if (!this._effects[effectIndex].isReady()) {
  75444. return false;
  75445. }
  75446. }
  75447. return true;
  75448. };
  75449. return BloomEffect;
  75450. }(BABYLON.PostProcessRenderEffect));
  75451. BABYLON.BloomEffect = BloomEffect;
  75452. })(BABYLON || (BABYLON = {}));
  75453. //# sourceMappingURL=babylon.bloomEffect.js.map
  75454. var BABYLON;
  75455. (function (BABYLON) {
  75456. /**
  75457. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75458. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75459. */
  75460. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75461. __extends(DefaultRenderingPipeline, _super);
  75462. /**
  75463. * @constructor
  75464. * @param {string} name - The rendering pipeline name
  75465. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75466. * @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)
  75467. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75468. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75469. */
  75470. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75471. if (automaticBuild === void 0) { automaticBuild = true; }
  75472. var _this = _super.call(this, scene.getEngine(), name) || this;
  75473. _this._originalCameras = [];
  75474. /**
  75475. * ID of the sharpen post process,
  75476. */
  75477. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75478. /**
  75479. * ID of the image processing post process;
  75480. */
  75481. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75482. /**
  75483. * ID of the Fast Approximate Anti-Aliasing post process;
  75484. */
  75485. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75486. /**
  75487. * ID of the chromatic aberration post process,
  75488. */
  75489. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75490. /**
  75491. * ID of the grain post process
  75492. */
  75493. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75494. /**
  75495. * Animations which can be used to tweak settings over a period of time
  75496. */
  75497. _this.animations = [];
  75498. _this._imageProcessingConfigurationObserver = null;
  75499. // Values
  75500. _this._sharpenEnabled = false;
  75501. _this._bloomEnabled = false;
  75502. _this._depthOfFieldEnabled = false;
  75503. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75504. _this._fxaaEnabled = false;
  75505. _this._imageProcessingEnabled = true;
  75506. _this._bloomScale = 0.5;
  75507. _this._chromaticAberrationEnabled = false;
  75508. _this._grainEnabled = false;
  75509. _this._buildAllowed = true;
  75510. _this._resizeObserver = null;
  75511. _this._hardwareScaleLevel = 1.0;
  75512. _this._bloomKernel = 64;
  75513. /**
  75514. * Specifies the weight of the bloom in the final rendering
  75515. */
  75516. _this._bloomWeight = 0.15;
  75517. /**
  75518. * Specifies the luma threshold for the area that will be blurred by the bloom
  75519. */
  75520. _this._bloomThreshold = 0.9;
  75521. _this._samples = 1;
  75522. _this._hasCleared = false;
  75523. _this._prevPostProcess = null;
  75524. _this._prevPrevPostProcess = null;
  75525. _this._cameras = cameras || [];
  75526. _this._originalCameras = _this._cameras.slice();
  75527. _this._buildAllowed = automaticBuild;
  75528. // Initialize
  75529. _this._scene = scene;
  75530. var caps = _this._scene.getEngine().getCaps();
  75531. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75532. // Misc
  75533. if (_this._hdr) {
  75534. if (caps.textureHalfFloatRender) {
  75535. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75536. }
  75537. else if (caps.textureFloatRender) {
  75538. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75539. }
  75540. }
  75541. else {
  75542. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75543. }
  75544. // Attach
  75545. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75546. var engine = _this._scene.getEngine();
  75547. // Create post processes before hand so they can be modified before enabled.
  75548. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75549. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75550. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75551. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75552. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75553. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75554. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75555. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75556. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75557. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75558. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75559. _this.bloomKernel = _this.bloomKernel;
  75560. });
  75561. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75562. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75563. });
  75564. _this._buildPipeline();
  75565. return _this;
  75566. }
  75567. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75568. get: function () {
  75569. return this._sharpenEnabled;
  75570. },
  75571. /**
  75572. * Enable or disable the sharpen process from the pipeline
  75573. */
  75574. set: function (enabled) {
  75575. if (this._sharpenEnabled === enabled) {
  75576. return;
  75577. }
  75578. this._sharpenEnabled = enabled;
  75579. this._buildPipeline();
  75580. },
  75581. enumerable: true,
  75582. configurable: true
  75583. });
  75584. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75585. /**
  75586. * Specifies the size of the bloom blur kernel, relative to the final output size
  75587. */
  75588. get: function () {
  75589. return this._bloomKernel;
  75590. },
  75591. set: function (value) {
  75592. this._bloomKernel = value;
  75593. this.bloom.kernel = value / this._hardwareScaleLevel;
  75594. },
  75595. enumerable: true,
  75596. configurable: true
  75597. });
  75598. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75599. get: function () {
  75600. return this._bloomWeight;
  75601. },
  75602. /**
  75603. * The strength of the bloom.
  75604. */
  75605. set: function (value) {
  75606. if (this._bloomWeight === value) {
  75607. return;
  75608. }
  75609. this.bloom.weight = value;
  75610. this._bloomWeight = value;
  75611. },
  75612. enumerable: true,
  75613. configurable: true
  75614. });
  75615. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75616. get: function () {
  75617. return this._bloomThreshold;
  75618. },
  75619. /**
  75620. * The strength of the bloom.
  75621. */
  75622. set: function (value) {
  75623. if (this._bloomThreshold === value) {
  75624. return;
  75625. }
  75626. this.bloom.threshold = value;
  75627. this._bloomThreshold = value;
  75628. },
  75629. enumerable: true,
  75630. configurable: true
  75631. });
  75632. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75633. get: function () {
  75634. return this._bloomScale;
  75635. },
  75636. /**
  75637. * The scale of the bloom, lower value will provide better performance.
  75638. */
  75639. set: function (value) {
  75640. if (this._bloomScale === value) {
  75641. return;
  75642. }
  75643. this._bloomScale = value;
  75644. // recreate bloom and dispose old as this setting is not dynamic
  75645. this._rebuildBloom();
  75646. this._buildPipeline();
  75647. },
  75648. enumerable: true,
  75649. configurable: true
  75650. });
  75651. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75652. get: function () {
  75653. return this._bloomEnabled;
  75654. },
  75655. /**
  75656. * Enable or disable the bloom from the pipeline
  75657. */
  75658. set: function (enabled) {
  75659. if (this._bloomEnabled === enabled) {
  75660. return;
  75661. }
  75662. this._bloomEnabled = enabled;
  75663. this._buildPipeline();
  75664. },
  75665. enumerable: true,
  75666. configurable: true
  75667. });
  75668. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75669. // recreate bloom and dispose old as this setting is not dynamic
  75670. var oldBloom = this.bloom;
  75671. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75672. this.bloom.threshold = oldBloom.threshold;
  75673. for (var i = 0; i < this._cameras.length; i++) {
  75674. oldBloom.disposeEffects(this._cameras[i]);
  75675. }
  75676. };
  75677. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75678. /**
  75679. * If the depth of field is enabled.
  75680. */
  75681. get: function () {
  75682. return this._depthOfFieldEnabled;
  75683. },
  75684. set: function (enabled) {
  75685. if (this._depthOfFieldEnabled === enabled) {
  75686. return;
  75687. }
  75688. this._depthOfFieldEnabled = enabled;
  75689. this._buildPipeline();
  75690. },
  75691. enumerable: true,
  75692. configurable: true
  75693. });
  75694. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75695. /**
  75696. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75697. */
  75698. get: function () {
  75699. return this._depthOfFieldBlurLevel;
  75700. },
  75701. set: function (value) {
  75702. if (this._depthOfFieldBlurLevel === value) {
  75703. return;
  75704. }
  75705. this._depthOfFieldBlurLevel = value;
  75706. // recreate dof and dispose old as this setting is not dynamic
  75707. var oldDof = this.depthOfField;
  75708. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75709. this.depthOfField.focalLength = oldDof.focalLength;
  75710. this.depthOfField.focusDistance = oldDof.focusDistance;
  75711. this.depthOfField.fStop = oldDof.fStop;
  75712. this.depthOfField.lensSize = oldDof.lensSize;
  75713. for (var i = 0; i < this._cameras.length; i++) {
  75714. oldDof.disposeEffects(this._cameras[i]);
  75715. }
  75716. this._buildPipeline();
  75717. },
  75718. enumerable: true,
  75719. configurable: true
  75720. });
  75721. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75722. get: function () {
  75723. return this._fxaaEnabled;
  75724. },
  75725. /**
  75726. * If the anti aliasing is enabled.
  75727. */
  75728. set: function (enabled) {
  75729. if (this._fxaaEnabled === enabled) {
  75730. return;
  75731. }
  75732. this._fxaaEnabled = enabled;
  75733. this._buildPipeline();
  75734. },
  75735. enumerable: true,
  75736. configurable: true
  75737. });
  75738. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75739. get: function () {
  75740. return this._samples;
  75741. },
  75742. /**
  75743. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75744. */
  75745. set: function (sampleCount) {
  75746. if (this._samples === sampleCount) {
  75747. return;
  75748. }
  75749. this._samples = sampleCount;
  75750. this._buildPipeline();
  75751. },
  75752. enumerable: true,
  75753. configurable: true
  75754. });
  75755. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75756. get: function () {
  75757. return this._imageProcessingEnabled;
  75758. },
  75759. /**
  75760. * If image processing is enabled.
  75761. */
  75762. set: function (enabled) {
  75763. if (this._imageProcessingEnabled === enabled) {
  75764. return;
  75765. }
  75766. this._imageProcessingEnabled = enabled;
  75767. this._buildPipeline();
  75768. },
  75769. enumerable: true,
  75770. configurable: true
  75771. });
  75772. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75773. get: function () {
  75774. return this._chromaticAberrationEnabled;
  75775. },
  75776. /**
  75777. * Enable or disable the chromaticAberration process from the pipeline
  75778. */
  75779. set: function (enabled) {
  75780. if (this._chromaticAberrationEnabled === enabled) {
  75781. return;
  75782. }
  75783. this._chromaticAberrationEnabled = enabled;
  75784. this._buildPipeline();
  75785. },
  75786. enumerable: true,
  75787. configurable: true
  75788. });
  75789. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75790. get: function () {
  75791. return this._grainEnabled;
  75792. },
  75793. /**
  75794. * Enable or disable the grain process from the pipeline
  75795. */
  75796. set: function (enabled) {
  75797. if (this._grainEnabled === enabled) {
  75798. return;
  75799. }
  75800. this._grainEnabled = enabled;
  75801. this._buildPipeline();
  75802. },
  75803. enumerable: true,
  75804. configurable: true
  75805. });
  75806. /**
  75807. * Force the compilation of the entire pipeline.
  75808. */
  75809. DefaultRenderingPipeline.prototype.prepare = function () {
  75810. var previousState = this._buildAllowed;
  75811. this._buildAllowed = true;
  75812. this._buildPipeline();
  75813. this._buildAllowed = previousState;
  75814. };
  75815. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75816. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75817. if (this._hasCleared) {
  75818. postProcess.autoClear = false;
  75819. }
  75820. else {
  75821. postProcess.autoClear = true;
  75822. this._scene.autoClear = false;
  75823. this._hasCleared = true;
  75824. }
  75825. if (!skipTextureSharing) {
  75826. if (this._prevPrevPostProcess) {
  75827. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75828. }
  75829. else {
  75830. postProcess.useOwnOutput();
  75831. }
  75832. if (this._prevPostProcess) {
  75833. this._prevPrevPostProcess = this._prevPostProcess;
  75834. }
  75835. this._prevPostProcess = postProcess;
  75836. }
  75837. };
  75838. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75839. var _this = this;
  75840. if (!this._buildAllowed) {
  75841. return;
  75842. }
  75843. this._scene.autoClear = true;
  75844. var engine = this._scene.getEngine();
  75845. this._disposePostProcesses();
  75846. if (this._cameras !== null) {
  75847. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75848. // get back cameras to be used to reattach pipeline
  75849. this._cameras = this._originalCameras.slice();
  75850. }
  75851. this._reset();
  75852. this._prevPostProcess = null;
  75853. this._prevPrevPostProcess = null;
  75854. this._hasCleared = false;
  75855. if (this.depthOfFieldEnabled) {
  75856. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75857. this.depthOfField.depthTexture = depthTexture;
  75858. if (!this.depthOfField._isReady()) {
  75859. this.depthOfField._updateEffects();
  75860. }
  75861. this.addEffect(this.depthOfField);
  75862. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75863. }
  75864. if (this.bloomEnabled) {
  75865. if (!this.bloom._isReady()) {
  75866. this.bloom._updateEffects();
  75867. }
  75868. this.addEffect(this.bloom);
  75869. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75870. }
  75871. if (this._imageProcessingEnabled) {
  75872. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75873. if (this._hdr) {
  75874. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75875. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75876. }
  75877. else {
  75878. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75879. }
  75880. }
  75881. if (this.sharpenEnabled) {
  75882. if (!this.sharpen.isReady()) {
  75883. this.sharpen.updateEffect();
  75884. }
  75885. this.addEffect(this._sharpenEffect);
  75886. this._setAutoClearAndTextureSharing(this.sharpen);
  75887. }
  75888. if (this.grainEnabled) {
  75889. if (!this.grain.isReady()) {
  75890. this.grain.updateEffect();
  75891. }
  75892. this.addEffect(this._grainEffect);
  75893. this._setAutoClearAndTextureSharing(this.grain);
  75894. }
  75895. if (this.chromaticAberrationEnabled) {
  75896. if (!this.chromaticAberration.isReady()) {
  75897. this.chromaticAberration.updateEffect();
  75898. }
  75899. this.addEffect(this._chromaticAberrationEffect);
  75900. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75901. }
  75902. if (this.fxaaEnabled) {
  75903. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75904. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75905. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75906. }
  75907. if (this._cameras !== null) {
  75908. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75909. }
  75910. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75911. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75912. }
  75913. };
  75914. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75915. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75916. for (var i = 0; i < this._cameras.length; i++) {
  75917. var camera = this._cameras[i];
  75918. if (this.imageProcessing) {
  75919. this.imageProcessing.dispose(camera);
  75920. }
  75921. if (this.fxaa) {
  75922. this.fxaa.dispose(camera);
  75923. }
  75924. // These are created in the constructor and should not be disposed on every pipeline change
  75925. if (disposeNonRecreated) {
  75926. if (this.sharpen) {
  75927. this.sharpen.dispose(camera);
  75928. }
  75929. if (this.depthOfField) {
  75930. this.depthOfField.disposeEffects(camera);
  75931. }
  75932. if (this.bloom) {
  75933. this.bloom.disposeEffects(camera);
  75934. }
  75935. if (this.chromaticAberration) {
  75936. this.chromaticAberration.dispose(camera);
  75937. }
  75938. if (this.grain) {
  75939. this.grain.dispose(camera);
  75940. }
  75941. }
  75942. }
  75943. this.imageProcessing = null;
  75944. this.fxaa = null;
  75945. if (disposeNonRecreated) {
  75946. this.sharpen = null;
  75947. this._sharpenEffect = null;
  75948. this.depthOfField = null;
  75949. this.bloom = null;
  75950. this.chromaticAberration = null;
  75951. this._chromaticAberrationEffect = null;
  75952. this.grain = null;
  75953. this._grainEffect = null;
  75954. }
  75955. };
  75956. /**
  75957. * Dispose of the pipeline and stop all post processes
  75958. */
  75959. DefaultRenderingPipeline.prototype.dispose = function () {
  75960. this._disposePostProcesses(true);
  75961. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75962. this._scene.autoClear = true;
  75963. if (this._resizeObserver) {
  75964. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75965. this._resizeObserver = null;
  75966. }
  75967. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75968. _super.prototype.dispose.call(this);
  75969. };
  75970. /**
  75971. * Serialize the rendering pipeline (Used when exporting)
  75972. * @returns the serialized object
  75973. */
  75974. DefaultRenderingPipeline.prototype.serialize = function () {
  75975. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75976. serializationObject.customType = "DefaultRenderingPipeline";
  75977. return serializationObject;
  75978. };
  75979. /**
  75980. * Parse the serialized pipeline
  75981. * @param source Source pipeline.
  75982. * @param scene The scene to load the pipeline to.
  75983. * @param rootUrl The URL of the serialized pipeline.
  75984. * @returns An instantiated pipeline from the serialized object.
  75985. */
  75986. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75987. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75988. };
  75989. __decorate([
  75990. BABYLON.serialize()
  75991. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75992. __decorate([
  75993. BABYLON.serialize()
  75994. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75995. __decorate([
  75996. BABYLON.serialize()
  75997. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75998. __decorate([
  75999. BABYLON.serialize()
  76000. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76001. __decorate([
  76002. BABYLON.serialize()
  76003. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76004. __decorate([
  76005. BABYLON.serialize()
  76006. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76007. __decorate([
  76008. BABYLON.serialize()
  76009. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76010. __decorate([
  76011. BABYLON.serialize()
  76012. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76013. __decorate([
  76014. BABYLON.serialize()
  76015. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76016. __decorate([
  76017. BABYLON.serialize()
  76018. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76019. __decorate([
  76020. BABYLON.serialize()
  76021. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76022. __decorate([
  76023. BABYLON.serialize()
  76024. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76025. __decorate([
  76026. BABYLON.serialize()
  76027. ], DefaultRenderingPipeline.prototype, "samples", null);
  76028. __decorate([
  76029. BABYLON.serialize()
  76030. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76031. __decorate([
  76032. BABYLON.serialize()
  76033. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76034. __decorate([
  76035. BABYLON.serialize()
  76036. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76037. return DefaultRenderingPipeline;
  76038. }(BABYLON.PostProcessRenderPipeline));
  76039. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76040. })(BABYLON || (BABYLON = {}));
  76041. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76042. var BABYLON;
  76043. (function (BABYLON) {
  76044. /**
  76045. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76046. */
  76047. var GeometryBufferRenderer = /** @class */ (function () {
  76048. /**
  76049. * Creates a new G Buffer for the scene
  76050. * @param scene The scene the buffer belongs to
  76051. * @param ratio How big is the buffer related to the main canvas.
  76052. */
  76053. function GeometryBufferRenderer(scene, ratio) {
  76054. if (ratio === void 0) { ratio = 1; }
  76055. this._enablePosition = false;
  76056. this._scene = scene;
  76057. this._ratio = ratio;
  76058. // Render target
  76059. this._createRenderTargets();
  76060. }
  76061. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76062. /**
  76063. * Set the render list (meshes to be rendered) used in the G buffer.
  76064. */
  76065. set: function (meshes) {
  76066. this._multiRenderTarget.renderList = meshes;
  76067. },
  76068. enumerable: true,
  76069. configurable: true
  76070. });
  76071. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76072. /**
  76073. * Gets wether or not G buffer are supported by the running hardware.
  76074. * This requires draw buffer supports
  76075. */
  76076. get: function () {
  76077. return this._multiRenderTarget.isSupported;
  76078. },
  76079. enumerable: true,
  76080. configurable: true
  76081. });
  76082. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76083. /**
  76084. * Gets wether or not position are enabled for the G buffer.
  76085. */
  76086. get: function () {
  76087. return this._enablePosition;
  76088. },
  76089. /**
  76090. * Sets wether or not position are enabled for the G buffer.
  76091. */
  76092. set: function (enable) {
  76093. this._enablePosition = enable;
  76094. this.dispose();
  76095. this._createRenderTargets();
  76096. },
  76097. enumerable: true,
  76098. configurable: true
  76099. });
  76100. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76101. /**
  76102. * Gets the scene associated with the buffer.
  76103. */
  76104. get: function () {
  76105. return this._scene;
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76111. /**
  76112. * Gets the ratio used by the buffer during its creation.
  76113. * How big is the buffer related to the main canvas.
  76114. */
  76115. get: function () {
  76116. return this._ratio;
  76117. },
  76118. enumerable: true,
  76119. configurable: true
  76120. });
  76121. /**
  76122. * Checks wether everything is ready to render a submesh to the G buffer.
  76123. * @param subMesh the submesh to check readiness for
  76124. * @param useInstances is the mesh drawn using instance or not
  76125. * @returns true if ready otherwise false
  76126. */
  76127. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76128. var material = subMesh.getMaterial();
  76129. if (material && material.disableDepthWrite) {
  76130. return false;
  76131. }
  76132. var defines = [];
  76133. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76134. var mesh = subMesh.getMesh();
  76135. // Alpha test
  76136. if (material && material.needAlphaTesting()) {
  76137. defines.push("#define ALPHATEST");
  76138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76139. attribs.push(BABYLON.VertexBuffer.UVKind);
  76140. defines.push("#define UV1");
  76141. }
  76142. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76143. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76144. defines.push("#define UV2");
  76145. }
  76146. }
  76147. // Buffers
  76148. if (this._enablePosition) {
  76149. defines.push("#define POSITION");
  76150. }
  76151. // Bones
  76152. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76153. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76154. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76155. if (mesh.numBoneInfluencers > 4) {
  76156. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76157. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76158. }
  76159. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76160. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76161. }
  76162. else {
  76163. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76164. }
  76165. // Instances
  76166. if (useInstances) {
  76167. defines.push("#define INSTANCES");
  76168. attribs.push("world0");
  76169. attribs.push("world1");
  76170. attribs.push("world2");
  76171. attribs.push("world3");
  76172. }
  76173. // Get correct effect
  76174. var join = defines.join("\n");
  76175. if (this._cachedDefines !== join) {
  76176. this._cachedDefines = join;
  76177. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76178. }
  76179. return this._effect.isReady();
  76180. };
  76181. /**
  76182. * Gets the current underlying G Buffer.
  76183. * @returns the buffer
  76184. */
  76185. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76186. return this._multiRenderTarget;
  76187. };
  76188. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76189. /**
  76190. * Gets the number of samples used to render the buffer (anti aliasing).
  76191. */
  76192. get: function () {
  76193. return this._multiRenderTarget.samples;
  76194. },
  76195. /**
  76196. * Sets the number of samples used to render the buffer (anti aliasing).
  76197. */
  76198. set: function (value) {
  76199. this._multiRenderTarget.samples = value;
  76200. },
  76201. enumerable: true,
  76202. configurable: true
  76203. });
  76204. /**
  76205. * Disposes the renderer and frees up associated resources.
  76206. */
  76207. GeometryBufferRenderer.prototype.dispose = function () {
  76208. this.getGBuffer().dispose();
  76209. };
  76210. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76211. var _this = this;
  76212. var engine = this._scene.getEngine();
  76213. var count = this._enablePosition ? 3 : 2;
  76214. 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 });
  76215. if (!this.isSupported) {
  76216. return;
  76217. }
  76218. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76219. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76220. this._multiRenderTarget.refreshRate = 1;
  76221. this._multiRenderTarget.renderParticles = false;
  76222. this._multiRenderTarget.renderList = null;
  76223. // set default depth value to 1.0 (far away)
  76224. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76225. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76226. });
  76227. // Custom render function
  76228. var renderSubMesh = function (subMesh) {
  76229. var mesh = subMesh.getRenderingMesh();
  76230. var scene = _this._scene;
  76231. var engine = scene.getEngine();
  76232. var material = subMesh.getMaterial();
  76233. if (!material) {
  76234. return;
  76235. }
  76236. // Culling
  76237. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76238. // Managing instances
  76239. var batch = mesh._getInstancesRenderList(subMesh._id);
  76240. if (batch.mustReturn) {
  76241. return;
  76242. }
  76243. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76244. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76245. engine.enableEffect(_this._effect);
  76246. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76247. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76248. _this._effect.setMatrix("view", scene.getViewMatrix());
  76249. // Alpha test
  76250. if (material && material.needAlphaTesting()) {
  76251. var alphaTexture = material.getAlphaTestTexture();
  76252. if (alphaTexture) {
  76253. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76254. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76255. }
  76256. }
  76257. // Bones
  76258. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76259. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76260. }
  76261. // Draw
  76262. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76263. }
  76264. };
  76265. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76266. var index;
  76267. if (depthOnlySubMeshes.length) {
  76268. engine.setColorWrite(false);
  76269. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76270. renderSubMesh(depthOnlySubMeshes.data[index]);
  76271. }
  76272. engine.setColorWrite(true);
  76273. }
  76274. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76275. renderSubMesh(opaqueSubMeshes.data[index]);
  76276. }
  76277. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76278. renderSubMesh(alphaTestSubMeshes.data[index]);
  76279. }
  76280. };
  76281. };
  76282. return GeometryBufferRenderer;
  76283. }());
  76284. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76285. })(BABYLON || (BABYLON = {}));
  76286. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76287. var BABYLON;
  76288. (function (BABYLON) {
  76289. var RefractionPostProcess = /** @class */ (function (_super) {
  76290. __extends(RefractionPostProcess, _super);
  76291. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76292. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76293. _this.color = color;
  76294. _this.depth = depth;
  76295. _this.colorLevel = colorLevel;
  76296. _this._ownRefractionTexture = true;
  76297. _this.onActivateObservable.add(function (cam) {
  76298. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76299. });
  76300. _this.onApplyObservable.add(function (effect) {
  76301. effect.setColor3("baseColor", _this.color);
  76302. effect.setFloat("depth", _this.depth);
  76303. effect.setFloat("colorLevel", _this.colorLevel);
  76304. effect.setTexture("refractionSampler", _this._refTexture);
  76305. });
  76306. return _this;
  76307. }
  76308. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76309. /**
  76310. * Gets or sets the refraction texture
  76311. * Please note that you are responsible for disposing the texture if you set it manually
  76312. */
  76313. get: function () {
  76314. return this._refTexture;
  76315. },
  76316. set: function (value) {
  76317. if (this._refTexture && this._ownRefractionTexture) {
  76318. this._refTexture.dispose();
  76319. }
  76320. this._refTexture = value;
  76321. this._ownRefractionTexture = false;
  76322. },
  76323. enumerable: true,
  76324. configurable: true
  76325. });
  76326. // Methods
  76327. RefractionPostProcess.prototype.dispose = function (camera) {
  76328. if (this._refTexture && this._ownRefractionTexture) {
  76329. this._refTexture.dispose();
  76330. this._refTexture = null;
  76331. }
  76332. _super.prototype.dispose.call(this, camera);
  76333. };
  76334. return RefractionPostProcess;
  76335. }(BABYLON.PostProcess));
  76336. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76337. })(BABYLON || (BABYLON = {}));
  76338. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76339. var BABYLON;
  76340. (function (BABYLON) {
  76341. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76342. __extends(BlackAndWhitePostProcess, _super);
  76343. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76344. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76345. _this.degree = 1;
  76346. _this.onApplyObservable.add(function (effect) {
  76347. effect.setFloat("degree", _this.degree);
  76348. });
  76349. return _this;
  76350. }
  76351. return BlackAndWhitePostProcess;
  76352. }(BABYLON.PostProcess));
  76353. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76354. })(BABYLON || (BABYLON = {}));
  76355. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76356. var BABYLON;
  76357. (function (BABYLON) {
  76358. /**
  76359. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76360. * input texture to perform effects such as edge detection or sharpening
  76361. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76362. */
  76363. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76364. __extends(ConvolutionPostProcess, _super);
  76365. /**
  76366. * Creates a new instance ConvolutionPostProcess
  76367. * @param name The name of the effect.
  76368. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76369. * @param options The required width/height ratio to downsize to before computing the render pass.
  76370. * @param camera The camera to apply the render pass to.
  76371. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76372. * @param engine The engine which the post process will be applied. (default: current engine)
  76373. * @param reusable If the post process can be reused on the same frame. (default: false)
  76374. * @param textureType Type of textures used when performing the post process. (default: 0)
  76375. */
  76376. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76377. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76378. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76379. _this.kernel = kernel;
  76380. _this.onApply = function (effect) {
  76381. effect.setFloat2("screenSize", _this.width, _this.height);
  76382. effect.setArray("kernel", _this.kernel);
  76383. };
  76384. return _this;
  76385. }
  76386. // Statics
  76387. /**
  76388. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76389. */
  76390. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76391. /**
  76392. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76393. */
  76394. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76395. /**
  76396. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76397. */
  76398. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76399. /**
  76400. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76401. */
  76402. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76403. /**
  76404. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76405. */
  76406. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76407. /**
  76408. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76409. */
  76410. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76411. return ConvolutionPostProcess;
  76412. }(BABYLON.PostProcess));
  76413. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76414. })(BABYLON || (BABYLON = {}));
  76415. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76416. var BABYLON;
  76417. (function (BABYLON) {
  76418. var FilterPostProcess = /** @class */ (function (_super) {
  76419. __extends(FilterPostProcess, _super);
  76420. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76421. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76422. _this.kernelMatrix = kernelMatrix;
  76423. _this.onApply = function (effect) {
  76424. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76425. };
  76426. return _this;
  76427. }
  76428. return FilterPostProcess;
  76429. }(BABYLON.PostProcess));
  76430. BABYLON.FilterPostProcess = FilterPostProcess;
  76431. })(BABYLON || (BABYLON = {}));
  76432. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76433. var BABYLON;
  76434. (function (BABYLON) {
  76435. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76436. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76437. __extends(VolumetricLightScatteringPostProcess, _super);
  76438. /**
  76439. * @constructor
  76440. * @param {string} name - The post-process name
  76441. * @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)
  76442. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76443. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76444. * @param {number} samples - The post-process quality, default 100
  76445. * @param {number} samplingMode - The post-process filtering mode
  76446. * @param {BABYLON.Engine} engine - The babylon engine
  76447. * @param {boolean} reusable - If the post-process is reusable
  76448. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76449. */
  76450. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76451. if (samples === void 0) { samples = 100; }
  76452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76453. 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;
  76454. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76455. /**
  76456. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76457. */
  76458. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76459. /**
  76460. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76461. */
  76462. _this.useCustomMeshPosition = false;
  76463. /**
  76464. * If the post-process should inverse the light scattering direction
  76465. */
  76466. _this.invert = true;
  76467. /**
  76468. * Array containing the excluded meshes not rendered in the internal pass
  76469. */
  76470. _this.excludedMeshes = new Array();
  76471. /**
  76472. * Controls the overall intensity of the post-process
  76473. */
  76474. _this.exposure = 0.3;
  76475. /**
  76476. * Dissipates each sample's contribution in range [0, 1]
  76477. */
  76478. _this.decay = 0.96815;
  76479. /**
  76480. * Controls the overall intensity of each sample
  76481. */
  76482. _this.weight = 0.58767;
  76483. /**
  76484. * Controls the density of each sample
  76485. */
  76486. _this.density = 0.926;
  76487. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76488. engine = scene.getEngine();
  76489. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76490. // Configure mesh
  76491. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76492. // Configure
  76493. _this._createPass(scene, ratio.passRatio || ratio);
  76494. _this.onActivate = function (camera) {
  76495. if (!_this.isSupported) {
  76496. _this.dispose(camera);
  76497. }
  76498. _this.onActivate = null;
  76499. };
  76500. _this.onApplyObservable.add(function (effect) {
  76501. _this._updateMeshScreenCoordinates(scene);
  76502. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76503. effect.setFloat("exposure", _this.exposure);
  76504. effect.setFloat("decay", _this.decay);
  76505. effect.setFloat("weight", _this.weight);
  76506. effect.setFloat("density", _this.density);
  76507. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76508. });
  76509. return _this;
  76510. }
  76511. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76512. get: function () {
  76513. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76514. return false;
  76515. },
  76516. set: function (useDiffuseColor) {
  76517. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76518. },
  76519. enumerable: true,
  76520. configurable: true
  76521. });
  76522. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76523. return "VolumetricLightScatteringPostProcess";
  76524. };
  76525. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76526. var mesh = subMesh.getMesh();
  76527. // Render this.mesh as default
  76528. if (mesh === this.mesh && mesh.material) {
  76529. return mesh.material.isReady(mesh);
  76530. }
  76531. var defines = [];
  76532. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76533. var material = subMesh.getMaterial();
  76534. // Alpha test
  76535. if (material) {
  76536. if (material.needAlphaTesting()) {
  76537. defines.push("#define ALPHATEST");
  76538. }
  76539. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76540. attribs.push(BABYLON.VertexBuffer.UVKind);
  76541. defines.push("#define UV1");
  76542. }
  76543. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76544. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76545. defines.push("#define UV2");
  76546. }
  76547. }
  76548. // Bones
  76549. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76550. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76551. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76552. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76553. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76554. }
  76555. else {
  76556. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76557. }
  76558. // Instances
  76559. if (useInstances) {
  76560. defines.push("#define INSTANCES");
  76561. attribs.push("world0");
  76562. attribs.push("world1");
  76563. attribs.push("world2");
  76564. attribs.push("world3");
  76565. }
  76566. // Get correct effect
  76567. var join = defines.join("\n");
  76568. if (this._cachedDefines !== join) {
  76569. this._cachedDefines = join;
  76570. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76571. }
  76572. return this._volumetricLightScatteringPass.isReady();
  76573. };
  76574. /**
  76575. * Sets the new light position for light scattering effect
  76576. * @param {BABYLON.Vector3} The new custom light position
  76577. */
  76578. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76579. this.customMeshPosition = position;
  76580. };
  76581. /**
  76582. * Returns the light position for light scattering effect
  76583. * @return {BABYLON.Vector3} The custom light position
  76584. */
  76585. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76586. return this.customMeshPosition;
  76587. };
  76588. /**
  76589. * Disposes the internal assets and detaches the post-process from the camera
  76590. */
  76591. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76592. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76593. if (rttIndex !== -1) {
  76594. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76595. }
  76596. this._volumetricLightScatteringRTT.dispose();
  76597. _super.prototype.dispose.call(this, camera);
  76598. };
  76599. /**
  76600. * Returns the render target texture used by the post-process
  76601. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76602. */
  76603. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76604. return this._volumetricLightScatteringRTT;
  76605. };
  76606. // Private methods
  76607. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76608. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76609. return true;
  76610. }
  76611. return false;
  76612. };
  76613. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76614. var _this = this;
  76615. var engine = scene.getEngine();
  76616. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76617. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76618. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76619. this._volumetricLightScatteringRTT.renderList = null;
  76620. this._volumetricLightScatteringRTT.renderParticles = false;
  76621. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76622. var camera = this.getCamera();
  76623. if (camera) {
  76624. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76625. }
  76626. else {
  76627. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76628. }
  76629. // Custom render function for submeshes
  76630. var renderSubMesh = function (subMesh) {
  76631. var mesh = subMesh.getRenderingMesh();
  76632. if (_this._meshExcluded(mesh)) {
  76633. return;
  76634. }
  76635. var material = subMesh.getMaterial();
  76636. if (!material) {
  76637. return;
  76638. }
  76639. var scene = mesh.getScene();
  76640. var engine = scene.getEngine();
  76641. // Culling
  76642. engine.setState(material.backFaceCulling);
  76643. // Managing instances
  76644. var batch = mesh._getInstancesRenderList(subMesh._id);
  76645. if (batch.mustReturn) {
  76646. return;
  76647. }
  76648. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76649. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76650. var effect = _this._volumetricLightScatteringPass;
  76651. if (mesh === _this.mesh) {
  76652. if (subMesh.effect) {
  76653. effect = subMesh.effect;
  76654. }
  76655. else {
  76656. effect = material.getEffect();
  76657. }
  76658. }
  76659. engine.enableEffect(effect);
  76660. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76661. if (mesh === _this.mesh) {
  76662. material.bind(mesh.getWorldMatrix(), mesh);
  76663. }
  76664. else {
  76665. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76666. // Alpha test
  76667. if (material && material.needAlphaTesting()) {
  76668. var alphaTexture = material.getAlphaTestTexture();
  76669. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76670. if (alphaTexture) {
  76671. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76672. }
  76673. }
  76674. // Bones
  76675. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76676. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76677. }
  76678. }
  76679. // Draw
  76680. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76681. }
  76682. };
  76683. // Render target texture callbacks
  76684. var savedSceneClearColor;
  76685. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76686. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76687. savedSceneClearColor = scene.clearColor;
  76688. scene.clearColor = sceneClearColor;
  76689. });
  76690. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76691. scene.clearColor = savedSceneClearColor;
  76692. });
  76693. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76694. var engine = scene.getEngine();
  76695. var index;
  76696. if (depthOnlySubMeshes.length) {
  76697. engine.setColorWrite(false);
  76698. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76699. renderSubMesh(depthOnlySubMeshes.data[index]);
  76700. }
  76701. engine.setColorWrite(true);
  76702. }
  76703. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76704. renderSubMesh(opaqueSubMeshes.data[index]);
  76705. }
  76706. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76707. renderSubMesh(alphaTestSubMeshes.data[index]);
  76708. }
  76709. if (transparentSubMeshes.length) {
  76710. // Sort sub meshes
  76711. for (index = 0; index < transparentSubMeshes.length; index++) {
  76712. var submesh = transparentSubMeshes.data[index];
  76713. var boundingInfo = submesh.getBoundingInfo();
  76714. if (boundingInfo && scene.activeCamera) {
  76715. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76716. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76717. }
  76718. }
  76719. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76720. sortedArray.sort(function (a, b) {
  76721. // Alpha index first
  76722. if (a._alphaIndex > b._alphaIndex) {
  76723. return 1;
  76724. }
  76725. if (a._alphaIndex < b._alphaIndex) {
  76726. return -1;
  76727. }
  76728. // Then distance to camera
  76729. if (a._distanceToCamera < b._distanceToCamera) {
  76730. return 1;
  76731. }
  76732. if (a._distanceToCamera > b._distanceToCamera) {
  76733. return -1;
  76734. }
  76735. return 0;
  76736. });
  76737. // Render sub meshes
  76738. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76739. for (index = 0; index < sortedArray.length; index++) {
  76740. renderSubMesh(sortedArray[index]);
  76741. }
  76742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76743. }
  76744. };
  76745. };
  76746. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76747. var transform = scene.getTransformMatrix();
  76748. var meshPosition;
  76749. if (this.useCustomMeshPosition) {
  76750. meshPosition = this.customMeshPosition;
  76751. }
  76752. else if (this.attachedNode) {
  76753. meshPosition = this.attachedNode.position;
  76754. }
  76755. else {
  76756. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76757. }
  76758. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76759. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76760. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76761. if (this.invert)
  76762. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76763. };
  76764. // Static methods
  76765. /**
  76766. * Creates a default mesh for the Volumeric Light Scattering post-process
  76767. * @param {string} The mesh name
  76768. * @param {BABYLON.Scene} The scene where to create the mesh
  76769. * @return {BABYLON.Mesh} the default mesh
  76770. */
  76771. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76772. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76773. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76774. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76775. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76776. mesh.material = material;
  76777. return mesh;
  76778. };
  76779. __decorate([
  76780. BABYLON.serializeAsVector3()
  76781. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76782. __decorate([
  76783. BABYLON.serialize()
  76784. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76785. __decorate([
  76786. BABYLON.serialize()
  76787. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76788. __decorate([
  76789. BABYLON.serializeAsMeshReference()
  76790. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76791. __decorate([
  76792. BABYLON.serialize()
  76793. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76794. __decorate([
  76795. BABYLON.serialize()
  76796. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76797. __decorate([
  76798. BABYLON.serialize()
  76799. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76800. __decorate([
  76801. BABYLON.serialize()
  76802. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76803. __decorate([
  76804. BABYLON.serialize()
  76805. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76806. return VolumetricLightScatteringPostProcess;
  76807. }(BABYLON.PostProcess));
  76808. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76809. })(BABYLON || (BABYLON = {}));
  76810. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76811. //
  76812. // This post-process allows the modification of rendered colors by using
  76813. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76814. //
  76815. // The object needs to be provided an url to a texture containing the color
  76816. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76817. // Use an image editing software to tweak the LUT to match your needs.
  76818. //
  76819. // For an example of a color LUT, see here:
  76820. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76821. // For explanations on color grading, see here:
  76822. // http://udn.epicgames.com/Three/ColorGrading.html
  76823. //
  76824. var BABYLON;
  76825. (function (BABYLON) {
  76826. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76827. __extends(ColorCorrectionPostProcess, _super);
  76828. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76829. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76830. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76831. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76832. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76833. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76834. _this.onApply = function (effect) {
  76835. effect.setTexture("colorTable", _this._colorTableTexture);
  76836. };
  76837. return _this;
  76838. }
  76839. return ColorCorrectionPostProcess;
  76840. }(BABYLON.PostProcess));
  76841. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76842. })(BABYLON || (BABYLON = {}));
  76843. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76844. var BABYLON;
  76845. (function (BABYLON) {
  76846. /** Defines operator used for tonemapping */
  76847. var TonemappingOperator;
  76848. (function (TonemappingOperator) {
  76849. /** Hable */
  76850. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76851. /** Reinhard */
  76852. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76853. /** HejiDawson */
  76854. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76855. /** Photographic */
  76856. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76857. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76858. ;
  76859. /**
  76860. * Defines a post process to apply tone mapping
  76861. */
  76862. var TonemapPostProcess = /** @class */ (function (_super) {
  76863. __extends(TonemapPostProcess, _super);
  76864. /**
  76865. * Creates a new TonemapPostProcess
  76866. * @param name defines the name of the postprocess
  76867. * @param _operator defines the operator to use
  76868. * @param exposureAdjustment defines the required exposure adjustement
  76869. * @param camera defines the camera to use (can be null)
  76870. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76871. * @param engine defines the hosting engine (can be ignore if camera is set)
  76872. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76873. */
  76874. function TonemapPostProcess(name, _operator,
  76875. /** Defines the required exposure adjustement */
  76876. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76878. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76879. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76880. _this._operator = _operator;
  76881. _this.exposureAdjustment = exposureAdjustment;
  76882. var defines = "#define ";
  76883. if (_this._operator === TonemappingOperator.Hable)
  76884. defines += "HABLE_TONEMAPPING";
  76885. else if (_this._operator === TonemappingOperator.Reinhard)
  76886. defines += "REINHARD_TONEMAPPING";
  76887. else if (_this._operator === TonemappingOperator.HejiDawson)
  76888. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76889. else if (_this._operator === TonemappingOperator.Photographic)
  76890. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76891. //sadly a second call to create the effect.
  76892. _this.updateEffect(defines);
  76893. _this.onApply = function (effect) {
  76894. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76895. };
  76896. return _this;
  76897. }
  76898. return TonemapPostProcess;
  76899. }(BABYLON.PostProcess));
  76900. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76901. })(BABYLON || (BABYLON = {}));
  76902. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76903. var BABYLON;
  76904. (function (BABYLON) {
  76905. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76906. __extends(DisplayPassPostProcess, _super);
  76907. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76908. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76909. }
  76910. return DisplayPassPostProcess;
  76911. }(BABYLON.PostProcess));
  76912. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76913. })(BABYLON || (BABYLON = {}));
  76914. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76915. var BABYLON;
  76916. (function (BABYLON) {
  76917. var HighlightsPostProcess = /** @class */ (function (_super) {
  76918. __extends(HighlightsPostProcess, _super);
  76919. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76921. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76922. }
  76923. return HighlightsPostProcess;
  76924. }(BABYLON.PostProcess));
  76925. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76926. })(BABYLON || (BABYLON = {}));
  76927. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76928. var BABYLON;
  76929. (function (BABYLON) {
  76930. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76931. __extends(ImageProcessingPostProcess, _super);
  76932. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76933. if (camera === void 0) { camera = null; }
  76934. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76935. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76936. _this._fromLinearSpace = true;
  76937. /**
  76938. * Defines cache preventing GC.
  76939. */
  76940. _this._defines = {
  76941. IMAGEPROCESSING: false,
  76942. VIGNETTE: false,
  76943. VIGNETTEBLENDMODEMULTIPLY: false,
  76944. VIGNETTEBLENDMODEOPAQUE: false,
  76945. TONEMAPPING: false,
  76946. CONTRAST: false,
  76947. COLORCURVES: false,
  76948. COLORGRADING: false,
  76949. COLORGRADING3D: false,
  76950. FROMLINEARSPACE: false,
  76951. SAMPLER3DGREENDEPTH: false,
  76952. SAMPLER3DBGRMAP: false,
  76953. IMAGEPROCESSINGPOSTPROCESS: false,
  76954. EXPOSURE: false,
  76955. };
  76956. // Setup the configuration as forced by the constructor. This would then not force the
  76957. // scene materials output in linear space and let untouched the default forward pass.
  76958. if (imageProcessingConfiguration) {
  76959. imageProcessingConfiguration.applyByPostProcess = true;
  76960. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76961. // This will cause the shader to be compiled
  76962. _this.fromLinearSpace = false;
  76963. }
  76964. // Setup the default processing configuration to the scene.
  76965. else {
  76966. _this._attachImageProcessingConfiguration(null, true);
  76967. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76968. }
  76969. _this.onApply = function (effect) {
  76970. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76971. };
  76972. return _this;
  76973. }
  76974. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76975. /**
  76976. * Gets the image processing configuration used either in this material.
  76977. */
  76978. get: function () {
  76979. return this._imageProcessingConfiguration;
  76980. },
  76981. /**
  76982. * Sets the Default image processing configuration used either in the this material.
  76983. *
  76984. * If sets to null, the scene one is in use.
  76985. */
  76986. set: function (value) {
  76987. this._attachImageProcessingConfiguration(value);
  76988. },
  76989. enumerable: true,
  76990. configurable: true
  76991. });
  76992. /**
  76993. * Attaches a new image processing configuration to the PBR Material.
  76994. * @param configuration
  76995. */
  76996. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76997. var _this = this;
  76998. if (doNotBuild === void 0) { doNotBuild = false; }
  76999. if (configuration === this._imageProcessingConfiguration) {
  77000. return;
  77001. }
  77002. // Detaches observer.
  77003. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77004. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77005. }
  77006. // Pick the scene configuration if needed.
  77007. if (!configuration) {
  77008. var scene = null;
  77009. var engine = this.getEngine();
  77010. var camera = this.getCamera();
  77011. if (camera) {
  77012. scene = camera.getScene();
  77013. }
  77014. else if (engine && engine.scenes) {
  77015. var scenes = engine.scenes;
  77016. scene = scenes[scenes.length - 1];
  77017. }
  77018. else {
  77019. scene = BABYLON.Engine.LastCreatedScene;
  77020. }
  77021. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77022. }
  77023. else {
  77024. this._imageProcessingConfiguration = configuration;
  77025. }
  77026. // Attaches observer.
  77027. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77028. _this._updateParameters();
  77029. });
  77030. // Ensure the effect will be rebuilt.
  77031. if (!doNotBuild) {
  77032. this._updateParameters();
  77033. }
  77034. };
  77035. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77036. /**
  77037. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77038. */
  77039. get: function () {
  77040. return this.imageProcessingConfiguration.colorCurves;
  77041. },
  77042. /**
  77043. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77044. */
  77045. set: function (value) {
  77046. this.imageProcessingConfiguration.colorCurves = value;
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77052. /**
  77053. * Gets wether the color curves effect is enabled.
  77054. */
  77055. get: function () {
  77056. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77057. },
  77058. /**
  77059. * Sets wether the color curves effect is enabled.
  77060. */
  77061. set: function (value) {
  77062. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77063. },
  77064. enumerable: true,
  77065. configurable: true
  77066. });
  77067. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77068. /**
  77069. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77070. */
  77071. get: function () {
  77072. return this.imageProcessingConfiguration.colorGradingTexture;
  77073. },
  77074. /**
  77075. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77076. */
  77077. set: function (value) {
  77078. this.imageProcessingConfiguration.colorGradingTexture = value;
  77079. },
  77080. enumerable: true,
  77081. configurable: true
  77082. });
  77083. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77084. /**
  77085. * Gets wether the color grading effect is enabled.
  77086. */
  77087. get: function () {
  77088. return this.imageProcessingConfiguration.colorGradingEnabled;
  77089. },
  77090. /**
  77091. * Gets wether the color grading effect is enabled.
  77092. */
  77093. set: function (value) {
  77094. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77100. /**
  77101. * Gets exposure used in the effect.
  77102. */
  77103. get: function () {
  77104. return this.imageProcessingConfiguration.exposure;
  77105. },
  77106. /**
  77107. * Sets exposure used in the effect.
  77108. */
  77109. set: function (value) {
  77110. this.imageProcessingConfiguration.exposure = value;
  77111. },
  77112. enumerable: true,
  77113. configurable: true
  77114. });
  77115. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77116. /**
  77117. * Gets wether tonemapping is enabled or not.
  77118. */
  77119. get: function () {
  77120. return this._imageProcessingConfiguration.toneMappingEnabled;
  77121. },
  77122. /**
  77123. * Sets wether tonemapping is enabled or not
  77124. */
  77125. set: function (value) {
  77126. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77127. },
  77128. enumerable: true,
  77129. configurable: true
  77130. });
  77131. ;
  77132. ;
  77133. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77134. /**
  77135. * Gets contrast used in the effect.
  77136. */
  77137. get: function () {
  77138. return this.imageProcessingConfiguration.contrast;
  77139. },
  77140. /**
  77141. * Sets contrast used in the effect.
  77142. */
  77143. set: function (value) {
  77144. this.imageProcessingConfiguration.contrast = value;
  77145. },
  77146. enumerable: true,
  77147. configurable: true
  77148. });
  77149. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77150. /**
  77151. * Gets Vignette stretch size.
  77152. */
  77153. get: function () {
  77154. return this.imageProcessingConfiguration.vignetteStretch;
  77155. },
  77156. /**
  77157. * Sets Vignette stretch size.
  77158. */
  77159. set: function (value) {
  77160. this.imageProcessingConfiguration.vignetteStretch = value;
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77166. /**
  77167. * Gets Vignette centre X Offset.
  77168. */
  77169. get: function () {
  77170. return this.imageProcessingConfiguration.vignetteCentreX;
  77171. },
  77172. /**
  77173. * Sets Vignette centre X Offset.
  77174. */
  77175. set: function (value) {
  77176. this.imageProcessingConfiguration.vignetteCentreX = value;
  77177. },
  77178. enumerable: true,
  77179. configurable: true
  77180. });
  77181. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77182. /**
  77183. * Gets Vignette centre Y Offset.
  77184. */
  77185. get: function () {
  77186. return this.imageProcessingConfiguration.vignetteCentreY;
  77187. },
  77188. /**
  77189. * Sets Vignette centre Y Offset.
  77190. */
  77191. set: function (value) {
  77192. this.imageProcessingConfiguration.vignetteCentreY = value;
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77198. /**
  77199. * Gets Vignette weight or intensity of the vignette effect.
  77200. */
  77201. get: function () {
  77202. return this.imageProcessingConfiguration.vignetteWeight;
  77203. },
  77204. /**
  77205. * Sets Vignette weight or intensity of the vignette effect.
  77206. */
  77207. set: function (value) {
  77208. this.imageProcessingConfiguration.vignetteWeight = value;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77214. /**
  77215. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77216. * if vignetteEnabled is set to true.
  77217. */
  77218. get: function () {
  77219. return this.imageProcessingConfiguration.vignetteColor;
  77220. },
  77221. /**
  77222. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77223. * if vignetteEnabled is set to true.
  77224. */
  77225. set: function (value) {
  77226. this.imageProcessingConfiguration.vignetteColor = value;
  77227. },
  77228. enumerable: true,
  77229. configurable: true
  77230. });
  77231. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77232. /**
  77233. * Gets Camera field of view used by the Vignette effect.
  77234. */
  77235. get: function () {
  77236. return this.imageProcessingConfiguration.vignetteCameraFov;
  77237. },
  77238. /**
  77239. * Sets Camera field of view used by the Vignette effect.
  77240. */
  77241. set: function (value) {
  77242. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77243. },
  77244. enumerable: true,
  77245. configurable: true
  77246. });
  77247. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77248. /**
  77249. * Gets the vignette blend mode allowing different kind of effect.
  77250. */
  77251. get: function () {
  77252. return this.imageProcessingConfiguration.vignetteBlendMode;
  77253. },
  77254. /**
  77255. * Sets the vignette blend mode allowing different kind of effect.
  77256. */
  77257. set: function (value) {
  77258. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77259. },
  77260. enumerable: true,
  77261. configurable: true
  77262. });
  77263. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77264. /**
  77265. * Gets wether the vignette effect is enabled.
  77266. */
  77267. get: function () {
  77268. return this.imageProcessingConfiguration.vignetteEnabled;
  77269. },
  77270. /**
  77271. * Sets wether the vignette effect is enabled.
  77272. */
  77273. set: function (value) {
  77274. this.imageProcessingConfiguration.vignetteEnabled = value;
  77275. },
  77276. enumerable: true,
  77277. configurable: true
  77278. });
  77279. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77280. /**
  77281. * Gets wether the input of the processing is in Gamma or Linear Space.
  77282. */
  77283. get: function () {
  77284. return this._fromLinearSpace;
  77285. },
  77286. /**
  77287. * Sets wether the input of the processing is in Gamma or Linear Space.
  77288. */
  77289. set: function (value) {
  77290. if (this._fromLinearSpace === value) {
  77291. return;
  77292. }
  77293. this._fromLinearSpace = value;
  77294. this._updateParameters();
  77295. },
  77296. enumerable: true,
  77297. configurable: true
  77298. });
  77299. ImageProcessingPostProcess.prototype.getClassName = function () {
  77300. return "ImageProcessingPostProcess";
  77301. };
  77302. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77303. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77304. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77305. var defines = "";
  77306. for (var define in this._defines) {
  77307. if (this._defines[define]) {
  77308. defines += "#define " + define + ";\r\n";
  77309. }
  77310. }
  77311. var samplers = ["textureSampler"];
  77312. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77313. var uniforms = ["scale"];
  77314. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77315. this.updateEffect(defines, uniforms, samplers);
  77316. };
  77317. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77318. _super.prototype.dispose.call(this, camera);
  77319. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77320. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77321. }
  77322. this.imageProcessingConfiguration.applyByPostProcess = false;
  77323. };
  77324. __decorate([
  77325. BABYLON.serialize()
  77326. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77327. return ImageProcessingPostProcess;
  77328. }(BABYLON.PostProcess));
  77329. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77330. })(BABYLON || (BABYLON = {}));
  77331. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77332. var BABYLON;
  77333. (function (BABYLON) {
  77334. /**
  77335. * Class used to store bone information
  77336. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77337. */
  77338. var Bone = /** @class */ (function (_super) {
  77339. __extends(Bone, _super);
  77340. /**
  77341. * Create a new bone
  77342. * @param name defines the bone name
  77343. * @param skeleton defines the parent skeleton
  77344. * @param parentBone defines the parent (can be null if the bone is the root)
  77345. * @param localMatrix defines the local matrix
  77346. * @param restPose defines the rest pose matrix
  77347. * @param baseMatrix defines the base matrix
  77348. * @param index defines index of the bone in the hiearchy
  77349. */
  77350. function Bone(
  77351. /**
  77352. * defines the bone name
  77353. */
  77354. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77355. if (parentBone === void 0) { parentBone = null; }
  77356. if (localMatrix === void 0) { localMatrix = null; }
  77357. if (restPose === void 0) { restPose = null; }
  77358. if (baseMatrix === void 0) { baseMatrix = null; }
  77359. if (index === void 0) { index = null; }
  77360. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77361. _this.name = name;
  77362. /**
  77363. * Gets the list of child bones
  77364. */
  77365. _this.children = new Array();
  77366. /** Gets the animations associated with this bone */
  77367. _this.animations = new Array();
  77368. /**
  77369. * @hidden Internal only
  77370. * Set this value to map this bone to a different index in the transform matrices
  77371. * Set this value to -1 to exclude the bone from the transform matrices
  77372. */
  77373. _this._index = null;
  77374. _this._absoluteTransform = new BABYLON.Matrix();
  77375. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77376. _this._scalingDeterminant = 1;
  77377. _this._worldTransform = new BABYLON.Matrix();
  77378. _this._needToDecompose = true;
  77379. _this._needToCompose = false;
  77380. _this._skeleton = skeleton;
  77381. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77382. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77383. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77384. _this._index = index;
  77385. skeleton.bones.push(_this);
  77386. _this.setParent(parentBone, false);
  77387. if (baseMatrix || localMatrix) {
  77388. _this._updateDifferenceMatrix();
  77389. }
  77390. return _this;
  77391. }
  77392. Object.defineProperty(Bone.prototype, "_matrix", {
  77393. /** @hidden */
  77394. get: function () {
  77395. this._compose();
  77396. return this._localMatrix;
  77397. },
  77398. /** @hidden */
  77399. set: function (value) {
  77400. this._localMatrix.copyFrom(value);
  77401. this._needToDecompose = true;
  77402. },
  77403. enumerable: true,
  77404. configurable: true
  77405. });
  77406. // Members
  77407. /**
  77408. * Gets the parent skeleton
  77409. * @returns a skeleton
  77410. */
  77411. Bone.prototype.getSkeleton = function () {
  77412. return this._skeleton;
  77413. };
  77414. /**
  77415. * Gets parent bone
  77416. * @returns a bone or null if the bone is the root of the bone hierarchy
  77417. */
  77418. Bone.prototype.getParent = function () {
  77419. return this._parent;
  77420. };
  77421. /**
  77422. * Sets the parent bone
  77423. * @param parent defines the parent (can be null if the bone is the root)
  77424. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77425. */
  77426. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77427. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77428. if (this._parent === parent) {
  77429. return;
  77430. }
  77431. if (this._parent) {
  77432. var index = this._parent.children.indexOf(this);
  77433. if (index !== -1) {
  77434. this._parent.children.splice(index, 1);
  77435. }
  77436. }
  77437. this._parent = parent;
  77438. if (this._parent) {
  77439. this._parent.children.push(this);
  77440. }
  77441. if (updateDifferenceMatrix) {
  77442. this._updateDifferenceMatrix();
  77443. }
  77444. this.markAsDirty();
  77445. };
  77446. /**
  77447. * Gets the local matrix
  77448. * @returns a matrix
  77449. */
  77450. Bone.prototype.getLocalMatrix = function () {
  77451. this._compose();
  77452. return this._localMatrix;
  77453. };
  77454. /**
  77455. * Gets the base matrix (initial matrix which remains unchanged)
  77456. * @returns a matrix
  77457. */
  77458. Bone.prototype.getBaseMatrix = function () {
  77459. return this._baseMatrix;
  77460. };
  77461. /**
  77462. * Gets the rest pose matrix
  77463. * @returns a matrix
  77464. */
  77465. Bone.prototype.getRestPose = function () {
  77466. return this._restPose;
  77467. };
  77468. /**
  77469. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77470. */
  77471. Bone.prototype.getWorldMatrix = function () {
  77472. return this._worldTransform;
  77473. };
  77474. /**
  77475. * Sets the local matrix to rest pose matrix
  77476. */
  77477. Bone.prototype.returnToRest = function () {
  77478. this.updateMatrix(this._restPose.clone());
  77479. };
  77480. /**
  77481. * Gets the inverse of the absolute transform matrix.
  77482. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77483. * @returns a matrix
  77484. */
  77485. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77486. return this._invertedAbsoluteTransform;
  77487. };
  77488. /**
  77489. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77490. * @returns a matrix
  77491. */
  77492. Bone.prototype.getAbsoluteTransform = function () {
  77493. return this._absoluteTransform;
  77494. };
  77495. Object.defineProperty(Bone.prototype, "position", {
  77496. // Properties (matches AbstractMesh properties)
  77497. /** Gets or sets current position (in local space) */
  77498. get: function () {
  77499. this._decompose();
  77500. return this._localPosition;
  77501. },
  77502. set: function (newPosition) {
  77503. this._decompose();
  77504. this._localPosition.copyFrom(newPosition);
  77505. this._markAsDirtyAndCompose();
  77506. },
  77507. enumerable: true,
  77508. configurable: true
  77509. });
  77510. Object.defineProperty(Bone.prototype, "rotation", {
  77511. /** Gets or sets current rotation (in local space) */
  77512. get: function () {
  77513. return this.getRotation();
  77514. },
  77515. set: function (newRotation) {
  77516. this.setRotation(newRotation);
  77517. },
  77518. enumerable: true,
  77519. configurable: true
  77520. });
  77521. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77522. /** Gets or sets current rotation quaternion (in local space) */
  77523. get: function () {
  77524. this._decompose();
  77525. return this._localRotation;
  77526. },
  77527. set: function (newRotation) {
  77528. this.setRotationQuaternion(newRotation);
  77529. },
  77530. enumerable: true,
  77531. configurable: true
  77532. });
  77533. Object.defineProperty(Bone.prototype, "scaling", {
  77534. /** Gets or sets current scaling (in local space) */
  77535. get: function () {
  77536. return this.getScale();
  77537. },
  77538. set: function (newScaling) {
  77539. this.setScale(newScaling);
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77545. /**
  77546. * Gets the animation properties override
  77547. */
  77548. get: function () {
  77549. return this._skeleton.animationPropertiesOverride;
  77550. },
  77551. enumerable: true,
  77552. configurable: true
  77553. });
  77554. // Methods
  77555. Bone.prototype._decompose = function () {
  77556. if (!this._needToDecompose) {
  77557. return;
  77558. }
  77559. this._needToDecompose = false;
  77560. if (!this._localScaling) {
  77561. this._localScaling = BABYLON.Vector3.Zero();
  77562. this._localRotation = BABYLON.Quaternion.Zero();
  77563. this._localPosition = BABYLON.Vector3.Zero();
  77564. }
  77565. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77566. };
  77567. Bone.prototype._compose = function () {
  77568. if (!this._needToCompose) {
  77569. return;
  77570. }
  77571. this._needToCompose = false;
  77572. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77573. };
  77574. /**
  77575. * Update the base and local matrices
  77576. * @param matrix defines the new base or local matrix
  77577. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77578. * @param updateLocalMatrix defines if the local matrix should be updated
  77579. */
  77580. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77581. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77582. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77583. this._baseMatrix.copyFrom(matrix);
  77584. if (updateDifferenceMatrix) {
  77585. this._updateDifferenceMatrix();
  77586. }
  77587. if (updateLocalMatrix) {
  77588. this._localMatrix.copyFrom(matrix);
  77589. this._markAsDirtyAndDecompose();
  77590. }
  77591. else {
  77592. this.markAsDirty();
  77593. }
  77594. };
  77595. /** @hidden */
  77596. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77597. if (updateChildren === void 0) { updateChildren = true; }
  77598. if (!rootMatrix) {
  77599. rootMatrix = this._baseMatrix;
  77600. }
  77601. if (this._parent) {
  77602. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77603. }
  77604. else {
  77605. this._absoluteTransform.copyFrom(rootMatrix);
  77606. }
  77607. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77608. if (updateChildren) {
  77609. for (var index = 0; index < this.children.length; index++) {
  77610. this.children[index]._updateDifferenceMatrix();
  77611. }
  77612. }
  77613. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77614. };
  77615. /**
  77616. * Flag the bone as dirty (Forcing it to update everything)
  77617. */
  77618. Bone.prototype.markAsDirty = function () {
  77619. this._currentRenderId++;
  77620. this._childRenderId++;
  77621. this._skeleton._markAsDirty();
  77622. };
  77623. Bone.prototype._markAsDirtyAndCompose = function () {
  77624. this.markAsDirty();
  77625. this._needToCompose = true;
  77626. };
  77627. Bone.prototype._markAsDirtyAndDecompose = function () {
  77628. this.markAsDirty();
  77629. this._needToDecompose = true;
  77630. };
  77631. /**
  77632. * Copy an animation range from another bone
  77633. * @param source defines the source bone
  77634. * @param rangeName defines the range name to copy
  77635. * @param frameOffset defines the frame offset
  77636. * @param rescaleAsRequired defines if rescaling must be applied if required
  77637. * @param skelDimensionsRatio defines the scaling ratio
  77638. * @returns true if operation was successful
  77639. */
  77640. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77641. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77642. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77643. // all animation may be coming from a library skeleton, so may need to create animation
  77644. if (this.animations.length === 0) {
  77645. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77646. this.animations[0].setKeys([]);
  77647. }
  77648. // get animation info / verify there is such a range from the source bone
  77649. var sourceRange = source.animations[0].getRange(rangeName);
  77650. if (!sourceRange) {
  77651. return false;
  77652. }
  77653. var from = sourceRange.from;
  77654. var to = sourceRange.to;
  77655. var sourceKeys = source.animations[0].getKeys();
  77656. // rescaling prep
  77657. var sourceBoneLength = source.length;
  77658. var sourceParent = source.getParent();
  77659. var parent = this.getParent();
  77660. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77661. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77662. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77663. var destKeys = this.animations[0].getKeys();
  77664. // loop vars declaration
  77665. var orig;
  77666. var origTranslation;
  77667. var mat;
  77668. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77669. orig = sourceKeys[key];
  77670. if (orig.frame >= from && orig.frame <= to) {
  77671. if (rescaleAsRequired) {
  77672. mat = orig.value.clone();
  77673. // scale based on parent ratio, when bone has parent
  77674. if (parentScalingReqd) {
  77675. origTranslation = mat.getTranslation();
  77676. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77677. // scale based on skeleton dimension ratio when root bone, and value is passed
  77678. }
  77679. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77680. origTranslation = mat.getTranslation();
  77681. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77682. // use original when root bone, and no data for skelDimensionsRatio
  77683. }
  77684. else {
  77685. mat = orig.value;
  77686. }
  77687. }
  77688. else {
  77689. mat = orig.value;
  77690. }
  77691. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77692. }
  77693. }
  77694. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77695. return true;
  77696. };
  77697. /**
  77698. * Translate the bone in local or world space
  77699. * @param vec The amount to translate the bone
  77700. * @param space The space that the translation is in
  77701. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77702. */
  77703. Bone.prototype.translate = function (vec, space, mesh) {
  77704. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77705. var lm = this.getLocalMatrix();
  77706. if (space == BABYLON.Space.LOCAL) {
  77707. lm.m[12] += vec.x;
  77708. lm.m[13] += vec.y;
  77709. lm.m[14] += vec.z;
  77710. }
  77711. else {
  77712. var wm = null;
  77713. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77714. if (mesh) {
  77715. wm = mesh.getWorldMatrix();
  77716. }
  77717. this._skeleton.computeAbsoluteTransforms();
  77718. var tmat = Bone._tmpMats[0];
  77719. var tvec = Bone._tmpVecs[0];
  77720. if (this._parent) {
  77721. if (mesh && wm) {
  77722. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77723. tmat.multiplyToRef(wm, tmat);
  77724. }
  77725. else {
  77726. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77727. }
  77728. }
  77729. tmat.m[12] = 0;
  77730. tmat.m[13] = 0;
  77731. tmat.m[14] = 0;
  77732. tmat.invert();
  77733. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77734. lm.m[12] += tvec.x;
  77735. lm.m[13] += tvec.y;
  77736. lm.m[14] += tvec.z;
  77737. }
  77738. this._markAsDirtyAndDecompose();
  77739. };
  77740. /**
  77741. * Set the postion of the bone in local or world space
  77742. * @param position The position to set the bone
  77743. * @param space The space that the position is in
  77744. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77745. */
  77746. Bone.prototype.setPosition = function (position, space, mesh) {
  77747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77748. var lm = this.getLocalMatrix();
  77749. if (space == BABYLON.Space.LOCAL) {
  77750. lm.m[12] = position.x;
  77751. lm.m[13] = position.y;
  77752. lm.m[14] = position.z;
  77753. }
  77754. else {
  77755. var wm = null;
  77756. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77757. if (mesh) {
  77758. wm = mesh.getWorldMatrix();
  77759. }
  77760. this._skeleton.computeAbsoluteTransforms();
  77761. var tmat = Bone._tmpMats[0];
  77762. var vec = Bone._tmpVecs[0];
  77763. if (this._parent) {
  77764. if (mesh && wm) {
  77765. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77766. tmat.multiplyToRef(wm, tmat);
  77767. }
  77768. else {
  77769. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77770. }
  77771. }
  77772. tmat.invert();
  77773. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77774. lm.m[12] = vec.x;
  77775. lm.m[13] = vec.y;
  77776. lm.m[14] = vec.z;
  77777. }
  77778. this._markAsDirtyAndDecompose();
  77779. };
  77780. /**
  77781. * Set the absolute position of the bone (world space)
  77782. * @param position The position to set the bone
  77783. * @param mesh The mesh that this bone is attached to
  77784. */
  77785. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77786. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77787. };
  77788. /**
  77789. * Scale the bone on the x, y and z axes (in local space)
  77790. * @param x The amount to scale the bone on the x axis
  77791. * @param y The amount to scale the bone on the y axis
  77792. * @param z The amount to scale the bone on the z axis
  77793. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77794. */
  77795. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77796. if (scaleChildren === void 0) { scaleChildren = false; }
  77797. var locMat = this.getLocalMatrix();
  77798. // Apply new scaling on top of current local matrix
  77799. var scaleMat = Bone._tmpMats[0];
  77800. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77801. scaleMat.multiplyToRef(locMat, locMat);
  77802. // Invert scaling matrix and apply the inverse to all children
  77803. scaleMat.invert();
  77804. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77805. var child = _a[_i];
  77806. var cm = child.getLocalMatrix();
  77807. cm.multiplyToRef(scaleMat, cm);
  77808. cm.m[12] *= x;
  77809. cm.m[13] *= y;
  77810. cm.m[14] *= z;
  77811. child._markAsDirtyAndDecompose();
  77812. }
  77813. this._markAsDirtyAndDecompose();
  77814. if (scaleChildren) {
  77815. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77816. var child = _c[_b];
  77817. child.scale(x, y, z, scaleChildren);
  77818. }
  77819. }
  77820. };
  77821. /**
  77822. * Set the bone scaling in local space
  77823. * @param scale defines the scaling vector
  77824. */
  77825. Bone.prototype.setScale = function (scale) {
  77826. this._decompose();
  77827. this._localScaling.copyFrom(scale);
  77828. this._markAsDirtyAndCompose();
  77829. };
  77830. /**
  77831. * Gets the current scaling in local space
  77832. * @returns the current scaling vector
  77833. */
  77834. Bone.prototype.getScale = function () {
  77835. this._decompose();
  77836. return this._localScaling;
  77837. };
  77838. /**
  77839. * Gets the current scaling in local space and stores it in a target vector
  77840. * @param result defines the target vector
  77841. */
  77842. Bone.prototype.getScaleToRef = function (result) {
  77843. this._decompose();
  77844. result.copyFrom(this._localScaling);
  77845. };
  77846. /**
  77847. * Set the yaw, pitch, and roll of the bone in local or world space
  77848. * @param yaw The rotation of the bone on the y axis
  77849. * @param pitch The rotation of the bone on the x axis
  77850. * @param roll The rotation of the bone on the z axis
  77851. * @param space The space that the axes of rotation are in
  77852. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77853. */
  77854. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77856. if (space === BABYLON.Space.LOCAL) {
  77857. var quat = Bone._tmpQuat;
  77858. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77859. this.setRotationQuaternion(quat, space, mesh);
  77860. return;
  77861. }
  77862. var rotMatInv = Bone._tmpMats[0];
  77863. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77864. return;
  77865. }
  77866. var rotMat = Bone._tmpMats[1];
  77867. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77868. rotMatInv.multiplyToRef(rotMat, rotMat);
  77869. this._rotateWithMatrix(rotMat, space, mesh);
  77870. };
  77871. /**
  77872. * Add a rotation to the bone on an axis in local or world space
  77873. * @param axis The axis to rotate the bone on
  77874. * @param amount The amount to rotate the bone
  77875. * @param space The space that the axis is in
  77876. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77877. */
  77878. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77880. var rmat = Bone._tmpMats[0];
  77881. rmat.m[12] = 0;
  77882. rmat.m[13] = 0;
  77883. rmat.m[14] = 0;
  77884. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77885. this._rotateWithMatrix(rmat, space, mesh);
  77886. };
  77887. /**
  77888. * Set the rotation of the bone to a particular axis angle in local or world space
  77889. * @param axis The axis to rotate the bone on
  77890. * @param angle The angle that the bone should be rotated to
  77891. * @param space The space that the axis is in
  77892. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77893. */
  77894. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77896. if (space === BABYLON.Space.LOCAL) {
  77897. var quat = Bone._tmpQuat;
  77898. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77899. this.setRotationQuaternion(quat, space, mesh);
  77900. return;
  77901. }
  77902. var rotMatInv = Bone._tmpMats[0];
  77903. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77904. return;
  77905. }
  77906. var rotMat = Bone._tmpMats[1];
  77907. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77908. rotMatInv.multiplyToRef(rotMat, rotMat);
  77909. this._rotateWithMatrix(rotMat, space, mesh);
  77910. };
  77911. /**
  77912. * Set the euler rotation of the bone in local of world space
  77913. * @param rotation The euler rotation that the bone should be set to
  77914. * @param space The space that the rotation is in
  77915. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77916. */
  77917. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77919. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77920. };
  77921. /**
  77922. * Set the quaternion rotation of the bone in local of world space
  77923. * @param quat The quaternion rotation that the bone should be set to
  77924. * @param space The space that the rotation is in
  77925. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77926. */
  77927. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77928. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77929. if (space === BABYLON.Space.LOCAL) {
  77930. this._decompose();
  77931. this._localRotation.copyFrom(quat);
  77932. this._markAsDirtyAndCompose();
  77933. return;
  77934. }
  77935. var rotMatInv = Bone._tmpMats[0];
  77936. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77937. return;
  77938. }
  77939. var rotMat = Bone._tmpMats[1];
  77940. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77941. rotMatInv.multiplyToRef(rotMat, rotMat);
  77942. this._rotateWithMatrix(rotMat, space, mesh);
  77943. };
  77944. /**
  77945. * Set the rotation matrix of the bone in local of world space
  77946. * @param rotMat The rotation matrix that the bone should be set to
  77947. * @param space The space that the rotation is in
  77948. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77949. */
  77950. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77951. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77952. if (space === BABYLON.Space.LOCAL) {
  77953. var quat = Bone._tmpQuat;
  77954. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77955. this.setRotationQuaternion(quat, space, mesh);
  77956. return;
  77957. }
  77958. var rotMatInv = Bone._tmpMats[0];
  77959. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77960. return;
  77961. }
  77962. var rotMat2 = Bone._tmpMats[1];
  77963. rotMat2.copyFrom(rotMat);
  77964. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77965. this._rotateWithMatrix(rotMat2, space, mesh);
  77966. };
  77967. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77968. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77969. var lmat = this.getLocalMatrix();
  77970. var lx = lmat.m[12];
  77971. var ly = lmat.m[13];
  77972. var lz = lmat.m[14];
  77973. var parent = this.getParent();
  77974. var parentScale = Bone._tmpMats[3];
  77975. var parentScaleInv = Bone._tmpMats[4];
  77976. if (parent && space == BABYLON.Space.WORLD) {
  77977. if (mesh) {
  77978. parentScale.copyFrom(mesh.getWorldMatrix());
  77979. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77980. }
  77981. else {
  77982. parentScale.copyFrom(parent.getAbsoluteTransform());
  77983. }
  77984. parentScaleInv.copyFrom(parentScale);
  77985. parentScaleInv.invert();
  77986. lmat.multiplyToRef(parentScale, lmat);
  77987. lmat.multiplyToRef(rmat, lmat);
  77988. lmat.multiplyToRef(parentScaleInv, lmat);
  77989. }
  77990. else {
  77991. if (space == BABYLON.Space.WORLD && mesh) {
  77992. parentScale.copyFrom(mesh.getWorldMatrix());
  77993. parentScaleInv.copyFrom(parentScale);
  77994. parentScaleInv.invert();
  77995. lmat.multiplyToRef(parentScale, lmat);
  77996. lmat.multiplyToRef(rmat, lmat);
  77997. lmat.multiplyToRef(parentScaleInv, lmat);
  77998. }
  77999. else {
  78000. lmat.multiplyToRef(rmat, lmat);
  78001. }
  78002. }
  78003. lmat.m[12] = lx;
  78004. lmat.m[13] = ly;
  78005. lmat.m[14] = lz;
  78006. this.computeAbsoluteTransforms();
  78007. this._markAsDirtyAndDecompose();
  78008. };
  78009. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78010. var scaleMatrix = Bone._tmpMats[2];
  78011. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78012. if (mesh) {
  78013. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78014. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78015. }
  78016. rotMatInv.invert();
  78017. if (isNaN(rotMatInv.m[0])) {
  78018. // Matrix failed to invert.
  78019. // This can happen if scale is zero for example.
  78020. return false;
  78021. }
  78022. scaleMatrix.m[0] *= this._scalingDeterminant;
  78023. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78024. return true;
  78025. };
  78026. /**
  78027. * Get the position of the bone in local or world space
  78028. * @param space The space that the returned position is in
  78029. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78030. * @returns The position of the bone
  78031. */
  78032. Bone.prototype.getPosition = function (space, mesh) {
  78033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78034. if (mesh === void 0) { mesh = null; }
  78035. var pos = BABYLON.Vector3.Zero();
  78036. this.getPositionToRef(space, mesh, pos);
  78037. return pos;
  78038. };
  78039. /**
  78040. * Copy the position of the bone to a vector3 in local or world space
  78041. * @param space The space that the returned position is in
  78042. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78043. * @param result The vector3 to copy the position to
  78044. */
  78045. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78047. if (space == BABYLON.Space.LOCAL) {
  78048. var lm = this.getLocalMatrix();
  78049. result.x = lm.m[12];
  78050. result.y = lm.m[13];
  78051. result.z = lm.m[14];
  78052. }
  78053. else {
  78054. var wm = null;
  78055. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78056. if (mesh) {
  78057. wm = mesh.getWorldMatrix();
  78058. }
  78059. this._skeleton.computeAbsoluteTransforms();
  78060. var tmat = Bone._tmpMats[0];
  78061. if (mesh && wm) {
  78062. tmat.copyFrom(this.getAbsoluteTransform());
  78063. tmat.multiplyToRef(wm, tmat);
  78064. }
  78065. else {
  78066. tmat = this.getAbsoluteTransform();
  78067. }
  78068. result.x = tmat.m[12];
  78069. result.y = tmat.m[13];
  78070. result.z = tmat.m[14];
  78071. }
  78072. };
  78073. /**
  78074. * Get the absolute position of the bone (world space)
  78075. * @param mesh The mesh that this bone is attached to
  78076. * @returns The absolute position of the bone
  78077. */
  78078. Bone.prototype.getAbsolutePosition = function (mesh) {
  78079. if (mesh === void 0) { mesh = null; }
  78080. var pos = BABYLON.Vector3.Zero();
  78081. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78082. return pos;
  78083. };
  78084. /**
  78085. * Copy the absolute position of the bone (world space) to the result param
  78086. * @param mesh The mesh that this bone is attached to
  78087. * @param result The vector3 to copy the absolute position to
  78088. */
  78089. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78090. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78091. };
  78092. /**
  78093. * Compute the absolute transforms of this bone and its children
  78094. */
  78095. Bone.prototype.computeAbsoluteTransforms = function () {
  78096. this._compose();
  78097. if (this._parent) {
  78098. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78099. }
  78100. else {
  78101. this._absoluteTransform.copyFrom(this._localMatrix);
  78102. var poseMatrix = this._skeleton.getPoseMatrix();
  78103. if (poseMatrix) {
  78104. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78105. }
  78106. }
  78107. var children = this.children;
  78108. var len = children.length;
  78109. for (var i = 0; i < len; i++) {
  78110. children[i].computeAbsoluteTransforms();
  78111. }
  78112. };
  78113. /**
  78114. * Get the world direction from an axis that is in the local space of the bone
  78115. * @param localAxis The local direction that is used to compute the world direction
  78116. * @param mesh The mesh that this bone is attached to
  78117. * @returns The world direction
  78118. */
  78119. Bone.prototype.getDirection = function (localAxis, mesh) {
  78120. if (mesh === void 0) { mesh = null; }
  78121. var result = BABYLON.Vector3.Zero();
  78122. this.getDirectionToRef(localAxis, mesh, result);
  78123. return result;
  78124. };
  78125. /**
  78126. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78127. * @param localAxis The local direction that is used to compute the world direction
  78128. * @param mesh The mesh that this bone is attached to
  78129. * @param result The vector3 that the world direction will be copied to
  78130. */
  78131. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78132. if (mesh === void 0) { mesh = null; }
  78133. var wm = null;
  78134. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78135. if (mesh) {
  78136. wm = mesh.getWorldMatrix();
  78137. }
  78138. this._skeleton.computeAbsoluteTransforms();
  78139. var mat = Bone._tmpMats[0];
  78140. mat.copyFrom(this.getAbsoluteTransform());
  78141. if (mesh && wm) {
  78142. mat.multiplyToRef(wm, mat);
  78143. }
  78144. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78145. result.normalize();
  78146. };
  78147. /**
  78148. * Get the euler rotation of the bone in local or world space
  78149. * @param space The space that the rotation should be in
  78150. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78151. * @returns The euler rotation
  78152. */
  78153. Bone.prototype.getRotation = function (space, mesh) {
  78154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78155. if (mesh === void 0) { mesh = null; }
  78156. var result = BABYLON.Vector3.Zero();
  78157. this.getRotationToRef(space, mesh, result);
  78158. return result;
  78159. };
  78160. /**
  78161. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78162. * @param space The space that the rotation should be in
  78163. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78164. * @param result The vector3 that the rotation should be copied to
  78165. */
  78166. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78168. if (mesh === void 0) { mesh = null; }
  78169. var quat = Bone._tmpQuat;
  78170. this.getRotationQuaternionToRef(space, mesh, quat);
  78171. quat.toEulerAnglesToRef(result);
  78172. };
  78173. /**
  78174. * Get the quaternion rotation of the bone in either local or world space
  78175. * @param space The space that the rotation should be in
  78176. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78177. * @returns The quaternion rotation
  78178. */
  78179. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78180. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78181. if (mesh === void 0) { mesh = null; }
  78182. var result = BABYLON.Quaternion.Identity();
  78183. this.getRotationQuaternionToRef(space, mesh, result);
  78184. return result;
  78185. };
  78186. /**
  78187. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78188. * @param space The space that the rotation should be in
  78189. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78190. * @param result The quaternion that the rotation should be copied to
  78191. */
  78192. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78193. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78194. if (mesh === void 0) { mesh = null; }
  78195. if (space == BABYLON.Space.LOCAL) {
  78196. this._decompose();
  78197. result.copyFrom(this._localRotation);
  78198. }
  78199. else {
  78200. var mat = Bone._tmpMats[0];
  78201. var amat = this.getAbsoluteTransform();
  78202. if (mesh) {
  78203. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78204. }
  78205. else {
  78206. mat.copyFrom(amat);
  78207. }
  78208. mat.m[0] *= this._scalingDeterminant;
  78209. mat.m[1] *= this._scalingDeterminant;
  78210. mat.m[2] *= this._scalingDeterminant;
  78211. mat.decompose(undefined, result, undefined);
  78212. }
  78213. };
  78214. /**
  78215. * Get the rotation matrix of the bone in local or world space
  78216. * @param space The space that the rotation should be in
  78217. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78218. * @returns The rotation matrix
  78219. */
  78220. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78222. var result = BABYLON.Matrix.Identity();
  78223. this.getRotationMatrixToRef(space, mesh, result);
  78224. return result;
  78225. };
  78226. /**
  78227. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78228. * @param space The space that the rotation should be in
  78229. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78230. * @param result The quaternion that the rotation should be copied to
  78231. */
  78232. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78234. if (space == BABYLON.Space.LOCAL) {
  78235. this.getLocalMatrix().getRotationMatrixToRef(result);
  78236. }
  78237. else {
  78238. var mat = Bone._tmpMats[0];
  78239. var amat = this.getAbsoluteTransform();
  78240. if (mesh) {
  78241. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78242. }
  78243. else {
  78244. mat.copyFrom(amat);
  78245. }
  78246. mat.m[0] *= this._scalingDeterminant;
  78247. mat.m[1] *= this._scalingDeterminant;
  78248. mat.m[2] *= this._scalingDeterminant;
  78249. mat.getRotationMatrixToRef(result);
  78250. }
  78251. };
  78252. /**
  78253. * Get the world position of a point that is in the local space of the bone
  78254. * @param position The local position
  78255. * @param mesh The mesh that this bone is attached to
  78256. * @returns The world position
  78257. */
  78258. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78259. if (mesh === void 0) { mesh = null; }
  78260. var result = BABYLON.Vector3.Zero();
  78261. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78262. return result;
  78263. };
  78264. /**
  78265. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78266. * @param position The local position
  78267. * @param mesh The mesh that this bone is attached to
  78268. * @param result The vector3 that the world position should be copied to
  78269. */
  78270. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78271. if (mesh === void 0) { mesh = null; }
  78272. var wm = null;
  78273. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78274. if (mesh) {
  78275. wm = mesh.getWorldMatrix();
  78276. }
  78277. this._skeleton.computeAbsoluteTransforms();
  78278. var tmat = Bone._tmpMats[0];
  78279. if (mesh && wm) {
  78280. tmat.copyFrom(this.getAbsoluteTransform());
  78281. tmat.multiplyToRef(wm, tmat);
  78282. }
  78283. else {
  78284. tmat = this.getAbsoluteTransform();
  78285. }
  78286. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78287. };
  78288. /**
  78289. * Get the local position of a point that is in world space
  78290. * @param position The world position
  78291. * @param mesh The mesh that this bone is attached to
  78292. * @returns The local position
  78293. */
  78294. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78295. if (mesh === void 0) { mesh = null; }
  78296. var result = BABYLON.Vector3.Zero();
  78297. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78298. return result;
  78299. };
  78300. /**
  78301. * Get the local position of a point that is in world space and copy it to the result param
  78302. * @param position The world position
  78303. * @param mesh The mesh that this bone is attached to
  78304. * @param result The vector3 that the local position should be copied to
  78305. */
  78306. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78307. if (mesh === void 0) { mesh = null; }
  78308. var wm = null;
  78309. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78310. if (mesh) {
  78311. wm = mesh.getWorldMatrix();
  78312. }
  78313. this._skeleton.computeAbsoluteTransforms();
  78314. var tmat = Bone._tmpMats[0];
  78315. tmat.copyFrom(this.getAbsoluteTransform());
  78316. if (mesh && wm) {
  78317. tmat.multiplyToRef(wm, tmat);
  78318. }
  78319. tmat.invert();
  78320. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78321. };
  78322. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78323. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78324. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78325. return Bone;
  78326. }(BABYLON.Node));
  78327. BABYLON.Bone = Bone;
  78328. })(BABYLON || (BABYLON = {}));
  78329. //# sourceMappingURL=babylon.bone.js.map
  78330. var BABYLON;
  78331. (function (BABYLON) {
  78332. /**
  78333. * Class used to apply inverse kinematics to bones
  78334. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78335. */
  78336. var BoneIKController = /** @class */ (function () {
  78337. /**
  78338. * Creates a new BoneIKController
  78339. * @param mesh defines the mesh to control
  78340. * @param bone defines the bone to control
  78341. * @param options defines options to set up the controller
  78342. */
  78343. function BoneIKController(mesh, bone, options) {
  78344. /**
  78345. * Gets or sets the target position
  78346. */
  78347. this.targetPosition = BABYLON.Vector3.Zero();
  78348. /**
  78349. * Gets or sets the pole target position
  78350. */
  78351. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78352. /**
  78353. * Gets or sets the pole target local offset
  78354. */
  78355. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78356. /**
  78357. * Gets or sets the pole angle
  78358. */
  78359. this.poleAngle = 0;
  78360. /**
  78361. * 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)
  78362. */
  78363. this.slerpAmount = 1;
  78364. this._bone1Quat = BABYLON.Quaternion.Identity();
  78365. this._bone1Mat = BABYLON.Matrix.Identity();
  78366. this._bone2Ang = Math.PI;
  78367. this._maxAngle = Math.PI;
  78368. this._rightHandedSystem = false;
  78369. this._bendAxis = BABYLON.Vector3.Right();
  78370. this._slerping = false;
  78371. this._adjustRoll = 0;
  78372. this._bone2 = bone;
  78373. this._bone1 = bone.getParent();
  78374. if (!this._bone1) {
  78375. return;
  78376. }
  78377. this.mesh = mesh;
  78378. var bonePos = bone.getPosition();
  78379. if (bone.getAbsoluteTransform().determinant() > 0) {
  78380. this._rightHandedSystem = true;
  78381. this._bendAxis.x = 0;
  78382. this._bendAxis.y = 0;
  78383. this._bendAxis.z = -1;
  78384. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78385. this._adjustRoll = Math.PI * .5;
  78386. this._bendAxis.z = 1;
  78387. }
  78388. }
  78389. if (this._bone1.length) {
  78390. var boneScale1 = this._bone1.getScale();
  78391. var boneScale2 = this._bone2.getScale();
  78392. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78393. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78394. }
  78395. else if (this._bone1.children[0]) {
  78396. mesh.computeWorldMatrix(true);
  78397. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78398. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78399. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78400. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78401. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78402. }
  78403. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78404. this.maxAngle = Math.PI;
  78405. if (options) {
  78406. if (options.targetMesh) {
  78407. this.targetMesh = options.targetMesh;
  78408. this.targetMesh.computeWorldMatrix(true);
  78409. }
  78410. if (options.poleTargetMesh) {
  78411. this.poleTargetMesh = options.poleTargetMesh;
  78412. this.poleTargetMesh.computeWorldMatrix(true);
  78413. }
  78414. else if (options.poleTargetBone) {
  78415. this.poleTargetBone = options.poleTargetBone;
  78416. }
  78417. else if (this._bone1.getParent()) {
  78418. this.poleTargetBone = this._bone1.getParent();
  78419. }
  78420. if (options.poleTargetLocalOffset) {
  78421. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78422. }
  78423. if (options.poleAngle) {
  78424. this.poleAngle = options.poleAngle;
  78425. }
  78426. if (options.bendAxis) {
  78427. this._bendAxis.copyFrom(options.bendAxis);
  78428. }
  78429. if (options.maxAngle) {
  78430. this.maxAngle = options.maxAngle;
  78431. }
  78432. if (options.slerpAmount) {
  78433. this.slerpAmount = options.slerpAmount;
  78434. }
  78435. }
  78436. }
  78437. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78438. /**
  78439. * Gets or sets maximum allowed angle
  78440. */
  78441. get: function () {
  78442. return this._maxAngle;
  78443. },
  78444. set: function (value) {
  78445. this._setMaxAngle(value);
  78446. },
  78447. enumerable: true,
  78448. configurable: true
  78449. });
  78450. BoneIKController.prototype._setMaxAngle = function (ang) {
  78451. if (ang < 0) {
  78452. ang = 0;
  78453. }
  78454. if (ang > Math.PI || ang == undefined) {
  78455. ang = Math.PI;
  78456. }
  78457. this._maxAngle = ang;
  78458. var a = this._bone1Length;
  78459. var b = this._bone2Length;
  78460. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78461. };
  78462. /**
  78463. * Force the controller to update the bones
  78464. */
  78465. BoneIKController.prototype.update = function () {
  78466. var bone1 = this._bone1;
  78467. if (!bone1) {
  78468. return;
  78469. }
  78470. var target = this.targetPosition;
  78471. var poleTarget = this.poleTargetPosition;
  78472. var mat1 = BoneIKController._tmpMats[0];
  78473. var mat2 = BoneIKController._tmpMats[1];
  78474. if (this.targetMesh) {
  78475. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78476. }
  78477. if (this.poleTargetBone) {
  78478. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78479. }
  78480. else if (this.poleTargetMesh) {
  78481. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78482. }
  78483. var bonePos = BoneIKController._tmpVecs[0];
  78484. var zaxis = BoneIKController._tmpVecs[1];
  78485. var xaxis = BoneIKController._tmpVecs[2];
  78486. var yaxis = BoneIKController._tmpVecs[3];
  78487. var upAxis = BoneIKController._tmpVecs[4];
  78488. var _tmpQuat = BoneIKController._tmpQuat;
  78489. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78490. poleTarget.subtractToRef(bonePos, upAxis);
  78491. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78492. upAxis.y = 1;
  78493. }
  78494. else {
  78495. upAxis.normalize();
  78496. }
  78497. target.subtractToRef(bonePos, yaxis);
  78498. yaxis.normalize();
  78499. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78500. zaxis.normalize();
  78501. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78502. xaxis.normalize();
  78503. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78504. var a = this._bone1Length;
  78505. var b = this._bone2Length;
  78506. var c = BABYLON.Vector3.Distance(bonePos, target);
  78507. if (this._maxReach > 0) {
  78508. c = Math.min(this._maxReach, c);
  78509. }
  78510. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78511. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78512. if (acosa > 1) {
  78513. acosa = 1;
  78514. }
  78515. if (acosb > 1) {
  78516. acosb = 1;
  78517. }
  78518. if (acosa < -1) {
  78519. acosa = -1;
  78520. }
  78521. if (acosb < -1) {
  78522. acosb = -1;
  78523. }
  78524. var angA = Math.acos(acosa);
  78525. var angB = Math.acos(acosb);
  78526. var angC = -angA - angB;
  78527. if (this._rightHandedSystem) {
  78528. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78529. mat2.multiplyToRef(mat1, mat1);
  78530. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78531. mat2.multiplyToRef(mat1, mat1);
  78532. }
  78533. else {
  78534. var _tmpVec = BoneIKController._tmpVecs[5];
  78535. _tmpVec.copyFrom(this._bendAxis);
  78536. _tmpVec.x *= -1;
  78537. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78538. mat2.multiplyToRef(mat1, mat1);
  78539. }
  78540. if (this.poleAngle) {
  78541. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78542. mat1.multiplyToRef(mat2, mat1);
  78543. }
  78544. if (this._bone1) {
  78545. if (this.slerpAmount < 1) {
  78546. if (!this._slerping) {
  78547. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78548. }
  78549. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78550. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78551. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78552. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78553. this._slerping = true;
  78554. }
  78555. else {
  78556. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78557. this._bone1Mat.copyFrom(mat1);
  78558. this._slerping = false;
  78559. }
  78560. }
  78561. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78562. this._bone2Ang = angC;
  78563. };
  78564. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78565. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78566. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78567. return BoneIKController;
  78568. }());
  78569. BABYLON.BoneIKController = BoneIKController;
  78570. })(BABYLON || (BABYLON = {}));
  78571. //# sourceMappingURL=babylon.boneIKController.js.map
  78572. var BABYLON;
  78573. (function (BABYLON) {
  78574. /**
  78575. * Class used to make a bone look toward a point in space
  78576. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78577. */
  78578. var BoneLookController = /** @class */ (function () {
  78579. /**
  78580. * Create a BoneLookController
  78581. * @param mesh the mesh that the bone belongs to
  78582. * @param bone the bone that will be looking to the target
  78583. * @param target the target Vector3 to look at
  78584. * @param settings optional settings:
  78585. * * maxYaw: the maximum angle the bone will yaw to
  78586. * * minYaw: the minimum angle the bone will yaw to
  78587. * * maxPitch: the maximum angle the bone will pitch to
  78588. * * minPitch: the minimum angle the bone will yaw to
  78589. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78590. * * upAxis: the up axis of the coordinate system
  78591. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78592. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78593. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78594. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78595. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78596. * * adjustRoll: used to make an adjustment to the roll of the bone
  78597. **/
  78598. function BoneLookController(mesh, bone, target, options) {
  78599. /**
  78600. * The up axis of the coordinate system that is used when the bone is rotated
  78601. */
  78602. this.upAxis = BABYLON.Vector3.Up();
  78603. /**
  78604. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78605. */
  78606. this.upAxisSpace = BABYLON.Space.LOCAL;
  78607. /**
  78608. * Used to make an adjustment to the yaw of the bone
  78609. */
  78610. this.adjustYaw = 0;
  78611. /**
  78612. * Used to make an adjustment to the pitch of the bone
  78613. */
  78614. this.adjustPitch = 0;
  78615. /**
  78616. * Used to make an adjustment to the roll of the bone
  78617. */
  78618. this.adjustRoll = 0;
  78619. /**
  78620. * 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)
  78621. */
  78622. this.slerpAmount = 1;
  78623. this._boneQuat = BABYLON.Quaternion.Identity();
  78624. this._slerping = false;
  78625. this._firstFrameSkipped = false;
  78626. this._fowardAxis = BABYLON.Vector3.Forward();
  78627. this.mesh = mesh;
  78628. this.bone = bone;
  78629. this.target = target;
  78630. if (options) {
  78631. if (options.adjustYaw) {
  78632. this.adjustYaw = options.adjustYaw;
  78633. }
  78634. if (options.adjustPitch) {
  78635. this.adjustPitch = options.adjustPitch;
  78636. }
  78637. if (options.adjustRoll) {
  78638. this.adjustRoll = options.adjustRoll;
  78639. }
  78640. if (options.maxYaw != null) {
  78641. this.maxYaw = options.maxYaw;
  78642. }
  78643. else {
  78644. this.maxYaw = Math.PI;
  78645. }
  78646. if (options.minYaw != null) {
  78647. this.minYaw = options.minYaw;
  78648. }
  78649. else {
  78650. this.minYaw = -Math.PI;
  78651. }
  78652. if (options.maxPitch != null) {
  78653. this.maxPitch = options.maxPitch;
  78654. }
  78655. else {
  78656. this.maxPitch = Math.PI;
  78657. }
  78658. if (options.minPitch != null) {
  78659. this.minPitch = options.minPitch;
  78660. }
  78661. else {
  78662. this.minPitch = -Math.PI;
  78663. }
  78664. if (options.slerpAmount != null) {
  78665. this.slerpAmount = options.slerpAmount;
  78666. }
  78667. if (options.upAxis != null) {
  78668. this.upAxis = options.upAxis;
  78669. }
  78670. if (options.upAxisSpace != null) {
  78671. this.upAxisSpace = options.upAxisSpace;
  78672. }
  78673. if (options.yawAxis != null || options.pitchAxis != null) {
  78674. var newYawAxis = BABYLON.Axis.Y;
  78675. var newPitchAxis = BABYLON.Axis.X;
  78676. if (options.yawAxis != null) {
  78677. newYawAxis = options.yawAxis.clone();
  78678. newYawAxis.normalize();
  78679. }
  78680. if (options.pitchAxis != null) {
  78681. newPitchAxis = options.pitchAxis.clone();
  78682. newPitchAxis.normalize();
  78683. }
  78684. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78685. this._transformYawPitch = BABYLON.Matrix.Identity();
  78686. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78687. this._transformYawPitchInv = this._transformYawPitch.clone();
  78688. this._transformYawPitch.invert();
  78689. }
  78690. }
  78691. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78692. this.upAxisSpace = BABYLON.Space.LOCAL;
  78693. }
  78694. }
  78695. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78696. /**
  78697. * Gets or sets the minimum yaw angle that the bone can look to
  78698. */
  78699. get: function () {
  78700. return this._minYaw;
  78701. },
  78702. set: function (value) {
  78703. this._minYaw = value;
  78704. this._minYawSin = Math.sin(value);
  78705. this._minYawCos = Math.cos(value);
  78706. if (this._maxYaw != null) {
  78707. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78708. this._yawRange = this._maxYaw - this._minYaw;
  78709. }
  78710. },
  78711. enumerable: true,
  78712. configurable: true
  78713. });
  78714. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78715. /**
  78716. * Gets or sets the maximum yaw angle that the bone can look to
  78717. */
  78718. get: function () {
  78719. return this._maxYaw;
  78720. },
  78721. set: function (value) {
  78722. this._maxYaw = value;
  78723. this._maxYawSin = Math.sin(value);
  78724. this._maxYawCos = Math.cos(value);
  78725. if (this._minYaw != null) {
  78726. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78727. this._yawRange = this._maxYaw - this._minYaw;
  78728. }
  78729. },
  78730. enumerable: true,
  78731. configurable: true
  78732. });
  78733. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78734. /**
  78735. * Gets or sets the minimum pitch angle that the bone can look to
  78736. */
  78737. get: function () {
  78738. return this._minPitch;
  78739. },
  78740. set: function (value) {
  78741. this._minPitch = value;
  78742. this._minPitchTan = Math.tan(value);
  78743. },
  78744. enumerable: true,
  78745. configurable: true
  78746. });
  78747. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78748. /**
  78749. * Gets or sets the maximum pitch angle that the bone can look to
  78750. */
  78751. get: function () {
  78752. return this._maxPitch;
  78753. },
  78754. set: function (value) {
  78755. this._maxPitch = value;
  78756. this._maxPitchTan = Math.tan(value);
  78757. },
  78758. enumerable: true,
  78759. configurable: true
  78760. });
  78761. /**
  78762. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78763. */
  78764. BoneLookController.prototype.update = function () {
  78765. //skip the first frame when slerping so that the mesh rotation is correct
  78766. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78767. this._firstFrameSkipped = true;
  78768. return;
  78769. }
  78770. var bone = this.bone;
  78771. var bonePos = BoneLookController._tmpVecs[0];
  78772. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78773. var target = this.target;
  78774. var _tmpMat1 = BoneLookController._tmpMats[0];
  78775. var _tmpMat2 = BoneLookController._tmpMats[1];
  78776. var mesh = this.mesh;
  78777. var parentBone = bone.getParent();
  78778. var upAxis = BoneLookController._tmpVecs[1];
  78779. upAxis.copyFrom(this.upAxis);
  78780. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78781. if (this._transformYawPitch) {
  78782. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78783. }
  78784. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78785. }
  78786. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78787. mesh.getDirectionToRef(upAxis, upAxis);
  78788. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78789. upAxis.normalize();
  78790. }
  78791. }
  78792. var checkYaw = false;
  78793. var checkPitch = false;
  78794. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78795. checkYaw = true;
  78796. }
  78797. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78798. checkPitch = true;
  78799. }
  78800. if (checkYaw || checkPitch) {
  78801. var spaceMat = BoneLookController._tmpMats[2];
  78802. var spaceMatInv = BoneLookController._tmpMats[3];
  78803. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78804. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78805. }
  78806. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78807. spaceMat.copyFrom(mesh.getWorldMatrix());
  78808. }
  78809. else {
  78810. var forwardAxis = BoneLookController._tmpVecs[2];
  78811. forwardAxis.copyFrom(this._fowardAxis);
  78812. if (this._transformYawPitch) {
  78813. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78814. }
  78815. if (parentBone) {
  78816. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78817. }
  78818. else {
  78819. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78820. }
  78821. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78822. rightAxis.normalize();
  78823. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78824. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78825. }
  78826. spaceMat.invertToRef(spaceMatInv);
  78827. var xzlen = null;
  78828. if (checkPitch) {
  78829. var localTarget = BoneLookController._tmpVecs[3];
  78830. target.subtractToRef(bonePos, localTarget);
  78831. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78832. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78833. var pitch = Math.atan2(localTarget.y, xzlen);
  78834. var newPitch = pitch;
  78835. if (pitch > this._maxPitch) {
  78836. localTarget.y = this._maxPitchTan * xzlen;
  78837. newPitch = this._maxPitch;
  78838. }
  78839. else if (pitch < this._minPitch) {
  78840. localTarget.y = this._minPitchTan * xzlen;
  78841. newPitch = this._minPitch;
  78842. }
  78843. if (pitch != newPitch) {
  78844. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78845. localTarget.addInPlace(bonePos);
  78846. target = localTarget;
  78847. }
  78848. }
  78849. if (checkYaw) {
  78850. var localTarget = BoneLookController._tmpVecs[4];
  78851. target.subtractToRef(bonePos, localTarget);
  78852. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78853. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78854. var newYaw = yaw;
  78855. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78856. if (xzlen == null) {
  78857. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78858. }
  78859. if (this._yawRange > Math.PI) {
  78860. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78861. localTarget.z = this._maxYawCos * xzlen;
  78862. localTarget.x = this._maxYawSin * xzlen;
  78863. newYaw = this._maxYaw;
  78864. }
  78865. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78866. localTarget.z = this._minYawCos * xzlen;
  78867. localTarget.x = this._minYawSin * xzlen;
  78868. newYaw = this._minYaw;
  78869. }
  78870. }
  78871. else {
  78872. if (yaw > this._maxYaw) {
  78873. localTarget.z = this._maxYawCos * xzlen;
  78874. localTarget.x = this._maxYawSin * xzlen;
  78875. newYaw = this._maxYaw;
  78876. }
  78877. else if (yaw < this._minYaw) {
  78878. localTarget.z = this._minYawCos * xzlen;
  78879. localTarget.x = this._minYawSin * xzlen;
  78880. newYaw = this._minYaw;
  78881. }
  78882. }
  78883. }
  78884. if (this._slerping && this._yawRange > Math.PI) {
  78885. //are we going to be crossing into the min/max region?
  78886. var boneFwd = BoneLookController._tmpVecs[8];
  78887. boneFwd.copyFrom(BABYLON.Axis.Z);
  78888. if (this._transformYawPitch) {
  78889. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78890. }
  78891. var boneRotMat = BoneLookController._tmpMats[4];
  78892. this._boneQuat.toRotationMatrix(boneRotMat);
  78893. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78894. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78895. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78896. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78897. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78898. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78899. if (angBtwTar > angBtwMidYaw) {
  78900. if (xzlen == null) {
  78901. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78902. }
  78903. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78904. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78905. if (angBtwMin < angBtwMax) {
  78906. newYaw = boneYaw + Math.PI * .75;
  78907. localTarget.z = Math.cos(newYaw) * xzlen;
  78908. localTarget.x = Math.sin(newYaw) * xzlen;
  78909. }
  78910. else {
  78911. newYaw = boneYaw - Math.PI * .75;
  78912. localTarget.z = Math.cos(newYaw) * xzlen;
  78913. localTarget.x = Math.sin(newYaw) * xzlen;
  78914. }
  78915. }
  78916. }
  78917. if (yaw != newYaw) {
  78918. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78919. localTarget.addInPlace(bonePos);
  78920. target = localTarget;
  78921. }
  78922. }
  78923. }
  78924. var zaxis = BoneLookController._tmpVecs[5];
  78925. var xaxis = BoneLookController._tmpVecs[6];
  78926. var yaxis = BoneLookController._tmpVecs[7];
  78927. var _tmpQuat = BoneLookController._tmpQuat;
  78928. target.subtractToRef(bonePos, zaxis);
  78929. zaxis.normalize();
  78930. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78931. xaxis.normalize();
  78932. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78933. yaxis.normalize();
  78934. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78935. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78936. return;
  78937. }
  78938. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78939. return;
  78940. }
  78941. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78942. return;
  78943. }
  78944. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78945. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78946. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78947. }
  78948. if (this.slerpAmount < 1) {
  78949. if (!this._slerping) {
  78950. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78951. }
  78952. if (this._transformYawPitch) {
  78953. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78954. }
  78955. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78956. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78957. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78958. this._slerping = true;
  78959. }
  78960. else {
  78961. if (this._transformYawPitch) {
  78962. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78963. }
  78964. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78965. this._slerping = false;
  78966. }
  78967. };
  78968. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78969. var angDiff = ang2 - ang1;
  78970. angDiff %= Math.PI * 2;
  78971. if (angDiff > Math.PI) {
  78972. angDiff -= Math.PI * 2;
  78973. }
  78974. else if (angDiff < -Math.PI) {
  78975. angDiff += Math.PI * 2;
  78976. }
  78977. return angDiff;
  78978. };
  78979. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78980. ang1 %= (2 * Math.PI);
  78981. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78982. ang2 %= (2 * Math.PI);
  78983. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78984. var ab = 0;
  78985. if (ang1 < ang2) {
  78986. ab = ang2 - ang1;
  78987. }
  78988. else {
  78989. ab = ang1 - ang2;
  78990. }
  78991. if (ab > Math.PI) {
  78992. ab = Math.PI * 2 - ab;
  78993. }
  78994. return ab;
  78995. };
  78996. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78997. ang %= (2 * Math.PI);
  78998. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78999. ang1 %= (2 * Math.PI);
  79000. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79001. ang2 %= (2 * Math.PI);
  79002. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79003. if (ang1 < ang2) {
  79004. if (ang > ang1 && ang < ang2) {
  79005. return true;
  79006. }
  79007. }
  79008. else {
  79009. if (ang > ang2 && ang < ang1) {
  79010. return true;
  79011. }
  79012. }
  79013. return false;
  79014. };
  79015. 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()];
  79016. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79017. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79018. return BoneLookController;
  79019. }());
  79020. BABYLON.BoneLookController = BoneLookController;
  79021. })(BABYLON || (BABYLON = {}));
  79022. //# sourceMappingURL=babylon.boneLookController.js.map
  79023. var BABYLON;
  79024. (function (BABYLON) {
  79025. /**
  79026. * Class used to handle skinning animations
  79027. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79028. */
  79029. var Skeleton = /** @class */ (function () {
  79030. /**
  79031. * Creates a new skeleton
  79032. * @param name defines the skeleton name
  79033. * @param id defines the skeleton Id
  79034. * @param scene defines the hosting scene
  79035. */
  79036. function Skeleton(
  79037. /** defines the skeleton name */
  79038. name,
  79039. /** defines the skeleton Id */
  79040. id, scene) {
  79041. this.name = name;
  79042. this.id = id;
  79043. /**
  79044. * Gets the list of child bones
  79045. */
  79046. this.bones = new Array();
  79047. /**
  79048. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79049. */
  79050. this.needInitialSkinMatrix = false;
  79051. this._isDirty = true;
  79052. this._meshesWithPoseMatrix = new Array();
  79053. this._identity = BABYLON.Matrix.Identity();
  79054. this._ranges = {};
  79055. this._lastAbsoluteTransformsUpdateId = -1;
  79056. /**
  79057. * Specifies if the skeleton should be serialized
  79058. */
  79059. this.doNotSerialize = false;
  79060. this._animationPropertiesOverride = null;
  79061. // Events
  79062. /**
  79063. * An observable triggered before computing the skeleton's matrices
  79064. */
  79065. this.onBeforeComputeObservable = new BABYLON.Observable();
  79066. this.bones = [];
  79067. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79068. scene.skeletons.push(this);
  79069. //make sure it will recalculate the matrix next time prepare is called.
  79070. this._isDirty = true;
  79071. }
  79072. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79073. /**
  79074. * Gets or sets the animation properties override
  79075. */
  79076. get: function () {
  79077. if (!this._animationPropertiesOverride) {
  79078. return this._scene.animationPropertiesOverride;
  79079. }
  79080. return this._animationPropertiesOverride;
  79081. },
  79082. set: function (value) {
  79083. this._animationPropertiesOverride = value;
  79084. },
  79085. enumerable: true,
  79086. configurable: true
  79087. });
  79088. // Members
  79089. /**
  79090. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79091. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79092. * @returns a Float32Array containing matrices data
  79093. */
  79094. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79095. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79096. return mesh._bonesTransformMatrices;
  79097. }
  79098. if (!this._transformMatrices) {
  79099. this.prepare();
  79100. }
  79101. return this._transformMatrices;
  79102. };
  79103. /**
  79104. * Gets the current hosting scene
  79105. * @returns a scene object
  79106. */
  79107. Skeleton.prototype.getScene = function () {
  79108. return this._scene;
  79109. };
  79110. // Methods
  79111. /**
  79112. * Gets a string representing the current skeleton data
  79113. * @param fullDetails defines a boolean indicating if we want a verbose version
  79114. * @returns a string representing the current skeleton data
  79115. */
  79116. Skeleton.prototype.toString = function (fullDetails) {
  79117. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79118. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79119. if (fullDetails) {
  79120. ret += ", Ranges: {";
  79121. var first = true;
  79122. for (var name_1 in this._ranges) {
  79123. if (first) {
  79124. ret += ", ";
  79125. first = false;
  79126. }
  79127. ret += name_1;
  79128. }
  79129. ret += "}";
  79130. }
  79131. return ret;
  79132. };
  79133. /**
  79134. * Get bone's index searching by name
  79135. * @param name defines bone's name to search for
  79136. * @return the indice of the bone. Returns -1 if not found
  79137. */
  79138. Skeleton.prototype.getBoneIndexByName = function (name) {
  79139. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79140. if (this.bones[boneIndex].name === name) {
  79141. return boneIndex;
  79142. }
  79143. }
  79144. return -1;
  79145. };
  79146. /**
  79147. * Creater a new animation range
  79148. * @param name defines the name of the range
  79149. * @param from defines the start key
  79150. * @param to defines the end key
  79151. */
  79152. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79153. // check name not already in use
  79154. if (!this._ranges[name]) {
  79155. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79156. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79157. if (this.bones[i].animations[0]) {
  79158. this.bones[i].animations[0].createRange(name, from, to);
  79159. }
  79160. }
  79161. }
  79162. };
  79163. /**
  79164. * Delete a specific animation range
  79165. * @param name defines the name of the range
  79166. * @param deleteFrames defines if frames must be removed as well
  79167. */
  79168. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79169. if (deleteFrames === void 0) { deleteFrames = true; }
  79170. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79171. if (this.bones[i].animations[0]) {
  79172. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79173. }
  79174. }
  79175. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79176. };
  79177. /**
  79178. * Gets a specific animation range
  79179. * @param name defines the name of the range to look for
  79180. * @returns the requested animation range or null if not found
  79181. */
  79182. Skeleton.prototype.getAnimationRange = function (name) {
  79183. return this._ranges[name];
  79184. };
  79185. /**
  79186. * Gets the list of all animation ranges defined on this skeleton
  79187. * @returns an array
  79188. */
  79189. Skeleton.prototype.getAnimationRanges = function () {
  79190. var animationRanges = [];
  79191. var name;
  79192. var i = 0;
  79193. for (name in this._ranges) {
  79194. animationRanges[i] = this._ranges[name];
  79195. i++;
  79196. }
  79197. return animationRanges;
  79198. };
  79199. /**
  79200. * Copy animation range from a source skeleton.
  79201. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79202. * @param source defines the source skeleton
  79203. * @param name defines the name of the range to copy
  79204. * @param rescaleAsRequired defines if rescaling must be applied if required
  79205. * @returns true if operation was successful
  79206. */
  79207. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79208. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79209. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79210. return false;
  79211. }
  79212. var ret = true;
  79213. var frameOffset = this._getHighestAnimationFrame() + 1;
  79214. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79215. var boneDict = {};
  79216. var sourceBones = source.bones;
  79217. var nBones;
  79218. var i;
  79219. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79220. boneDict[sourceBones[i].name] = sourceBones[i];
  79221. }
  79222. if (this.bones.length !== sourceBones.length) {
  79223. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79224. ret = false;
  79225. }
  79226. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79227. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79228. var boneName = this.bones[i].name;
  79229. var sourceBone = boneDict[boneName];
  79230. if (sourceBone) {
  79231. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79232. }
  79233. else {
  79234. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79235. ret = false;
  79236. }
  79237. }
  79238. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79239. var range = source.getAnimationRange(name);
  79240. if (range) {
  79241. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79242. }
  79243. return ret;
  79244. };
  79245. /**
  79246. * Forces the skeleton to go to rest pose
  79247. */
  79248. Skeleton.prototype.returnToRest = function () {
  79249. for (var index = 0; index < this.bones.length; index++) {
  79250. this.bones[index].returnToRest();
  79251. }
  79252. };
  79253. Skeleton.prototype._getHighestAnimationFrame = function () {
  79254. var ret = 0;
  79255. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79256. if (this.bones[i].animations[0]) {
  79257. var highest = this.bones[i].animations[0].getHighestFrame();
  79258. if (ret < highest) {
  79259. ret = highest;
  79260. }
  79261. }
  79262. }
  79263. return ret;
  79264. };
  79265. /**
  79266. * Begin a specific animation range
  79267. * @param name defines the name of the range to start
  79268. * @param loop defines if looping must be turned on (false by default)
  79269. * @param speedRatio defines the speed ratio to apply (1 by default)
  79270. * @param onAnimationEnd defines a callback which will be called when animation will end
  79271. * @returns a new animatable
  79272. */
  79273. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79274. var range = this.getAnimationRange(name);
  79275. if (!range) {
  79276. return null;
  79277. }
  79278. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79279. };
  79280. /** @hidden */
  79281. Skeleton.prototype._markAsDirty = function () {
  79282. this._isDirty = true;
  79283. };
  79284. /** @hidden */
  79285. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79286. this._meshesWithPoseMatrix.push(mesh);
  79287. };
  79288. /** @hidden */
  79289. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79290. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79291. if (index > -1) {
  79292. this._meshesWithPoseMatrix.splice(index, 1);
  79293. }
  79294. };
  79295. /** @hidden */
  79296. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79297. this.onBeforeComputeObservable.notifyObservers(this);
  79298. for (var index = 0; index < this.bones.length; index++) {
  79299. var bone = this.bones[index];
  79300. var parentBone = bone.getParent();
  79301. if (parentBone) {
  79302. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79303. }
  79304. else {
  79305. if (initialSkinMatrix) {
  79306. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79307. }
  79308. else {
  79309. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79310. }
  79311. }
  79312. if (bone._index !== -1) {
  79313. var mappedIndex = bone._index === null ? index : bone._index;
  79314. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79315. }
  79316. }
  79317. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79318. };
  79319. /**
  79320. * Build all resources required to render a skeleton
  79321. */
  79322. Skeleton.prototype.prepare = function () {
  79323. if (!this._isDirty) {
  79324. return;
  79325. }
  79326. if (this.needInitialSkinMatrix) {
  79327. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79328. var mesh = this._meshesWithPoseMatrix[index];
  79329. var poseMatrix = mesh.getPoseMatrix();
  79330. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79331. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79332. }
  79333. if (this._synchronizedWithMesh !== mesh) {
  79334. this._synchronizedWithMesh = mesh;
  79335. // Prepare bones
  79336. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79337. var bone = this.bones[boneIndex];
  79338. if (!bone.getParent()) {
  79339. var matrix = bone.getBaseMatrix();
  79340. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79341. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79342. }
  79343. }
  79344. }
  79345. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79346. }
  79347. }
  79348. else {
  79349. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79350. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79351. }
  79352. this._computeTransformMatrices(this._transformMatrices, null);
  79353. }
  79354. this._isDirty = false;
  79355. this._scene._activeBones.addCount(this.bones.length, false);
  79356. };
  79357. /**
  79358. * Gets the list of animatables currently running for this skeleton
  79359. * @returns an array of animatables
  79360. */
  79361. Skeleton.prototype.getAnimatables = function () {
  79362. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79363. this._animatables = [];
  79364. for (var index = 0; index < this.bones.length; index++) {
  79365. this._animatables.push(this.bones[index]);
  79366. }
  79367. }
  79368. return this._animatables;
  79369. };
  79370. /**
  79371. * Clone the current skeleton
  79372. * @param name defines the name of the new skeleton
  79373. * @param id defines the id of the enw skeleton
  79374. * @returns the new skeleton
  79375. */
  79376. Skeleton.prototype.clone = function (name, id) {
  79377. var result = new Skeleton(name, id || name, this._scene);
  79378. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79379. for (var index = 0; index < this.bones.length; index++) {
  79380. var source = this.bones[index];
  79381. var parentBone = null;
  79382. var parent_1 = source.getParent();
  79383. if (parent_1) {
  79384. var parentIndex = this.bones.indexOf(parent_1);
  79385. parentBone = result.bones[parentIndex];
  79386. }
  79387. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79388. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79389. }
  79390. if (this._ranges) {
  79391. result._ranges = {};
  79392. for (var rangeName in this._ranges) {
  79393. var range = this._ranges[rangeName];
  79394. if (range) {
  79395. result._ranges[rangeName] = range.clone();
  79396. }
  79397. }
  79398. }
  79399. this._isDirty = true;
  79400. return result;
  79401. };
  79402. /**
  79403. * Enable animation blending for this skeleton
  79404. * @param blendingSpeed defines the blending speed to apply
  79405. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79406. */
  79407. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79408. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79409. this.bones.forEach(function (bone) {
  79410. bone.animations.forEach(function (animation) {
  79411. animation.enableBlending = true;
  79412. animation.blendingSpeed = blendingSpeed;
  79413. });
  79414. });
  79415. };
  79416. /**
  79417. * Releases all resources associated with the current skeleton
  79418. */
  79419. Skeleton.prototype.dispose = function () {
  79420. this._meshesWithPoseMatrix = [];
  79421. // Animations
  79422. this.getScene().stopAnimation(this);
  79423. // Remove from scene
  79424. this.getScene().removeSkeleton(this);
  79425. };
  79426. /**
  79427. * Serialize the skeleton in a JSON object
  79428. * @returns a JSON object
  79429. */
  79430. Skeleton.prototype.serialize = function () {
  79431. var serializationObject = {};
  79432. serializationObject.name = this.name;
  79433. serializationObject.id = this.id;
  79434. if (this.dimensionsAtRest) {
  79435. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79436. }
  79437. serializationObject.bones = [];
  79438. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79439. for (var index = 0; index < this.bones.length; index++) {
  79440. var bone = this.bones[index];
  79441. var parent_2 = bone.getParent();
  79442. var serializedBone = {
  79443. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79444. name: bone.name,
  79445. matrix: bone.getBaseMatrix().toArray(),
  79446. rest: bone.getRestPose().toArray()
  79447. };
  79448. serializationObject.bones.push(serializedBone);
  79449. if (bone.length) {
  79450. serializedBone.length = bone.length;
  79451. }
  79452. if (bone.metadata) {
  79453. serializedBone.metadata = bone.metadata;
  79454. }
  79455. if (bone.animations && bone.animations.length > 0) {
  79456. serializedBone.animation = bone.animations[0].serialize();
  79457. }
  79458. serializationObject.ranges = [];
  79459. for (var name in this._ranges) {
  79460. var source = this._ranges[name];
  79461. if (!source) {
  79462. continue;
  79463. }
  79464. var range = {};
  79465. range.name = name;
  79466. range.from = source.from;
  79467. range.to = source.to;
  79468. serializationObject.ranges.push(range);
  79469. }
  79470. }
  79471. return serializationObject;
  79472. };
  79473. /**
  79474. * Creates a new skeleton from serialized data
  79475. * @param parsedSkeleton defines the serialized data
  79476. * @param scene defines the hosting scene
  79477. * @returns a new skeleton
  79478. */
  79479. Skeleton.Parse = function (parsedSkeleton, scene) {
  79480. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79481. if (parsedSkeleton.dimensionsAtRest) {
  79482. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79483. }
  79484. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79485. var index;
  79486. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79487. var parsedBone = parsedSkeleton.bones[index];
  79488. var parentBone = null;
  79489. if (parsedBone.parentBoneIndex > -1) {
  79490. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79491. }
  79492. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79493. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79494. if (parsedBone.length) {
  79495. bone.length = parsedBone.length;
  79496. }
  79497. if (parsedBone.metadata) {
  79498. bone.metadata = parsedBone.metadata;
  79499. }
  79500. if (parsedBone.animation) {
  79501. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79502. }
  79503. }
  79504. // placed after bones, so createAnimationRange can cascade down
  79505. if (parsedSkeleton.ranges) {
  79506. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79507. var data = parsedSkeleton.ranges[index];
  79508. skeleton.createAnimationRange(data.name, data.from, data.to);
  79509. }
  79510. }
  79511. return skeleton;
  79512. };
  79513. /**
  79514. * Compute all node absolute transforms
  79515. * @param forceUpdate defines if computation must be done even if cache is up to date
  79516. */
  79517. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79518. if (forceUpdate === void 0) { forceUpdate = false; }
  79519. var renderId = this._scene.getRenderId();
  79520. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79521. this.bones[0].computeAbsoluteTransforms();
  79522. this._lastAbsoluteTransformsUpdateId = renderId;
  79523. }
  79524. };
  79525. /**
  79526. * Gets the root pose matrix
  79527. * @returns a matrix
  79528. */
  79529. Skeleton.prototype.getPoseMatrix = function () {
  79530. var poseMatrix = null;
  79531. if (this._meshesWithPoseMatrix.length > 0) {
  79532. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79533. }
  79534. return poseMatrix;
  79535. };
  79536. /**
  79537. * Sorts bones per internal index
  79538. */
  79539. Skeleton.prototype.sortBones = function () {
  79540. var bones = new Array();
  79541. var visited = new Array(this.bones.length);
  79542. for (var index = 0; index < this.bones.length; index++) {
  79543. this._sortBones(index, bones, visited);
  79544. }
  79545. this.bones = bones;
  79546. };
  79547. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79548. if (visited[index]) {
  79549. return;
  79550. }
  79551. visited[index] = true;
  79552. var bone = this.bones[index];
  79553. if (bone._index === undefined) {
  79554. bone._index = index;
  79555. }
  79556. var parentBone = bone.getParent();
  79557. if (parentBone) {
  79558. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79559. }
  79560. bones.push(bone);
  79561. };
  79562. return Skeleton;
  79563. }());
  79564. BABYLON.Skeleton = Skeleton;
  79565. })(BABYLON || (BABYLON = {}));
  79566. //# sourceMappingURL=babylon.skeleton.js.map
  79567. var BABYLON;
  79568. (function (BABYLON) {
  79569. var SphericalPolynomial = /** @class */ (function () {
  79570. function SphericalPolynomial() {
  79571. this.x = BABYLON.Vector3.Zero();
  79572. this.y = BABYLON.Vector3.Zero();
  79573. this.z = BABYLON.Vector3.Zero();
  79574. this.xx = BABYLON.Vector3.Zero();
  79575. this.yy = BABYLON.Vector3.Zero();
  79576. this.zz = BABYLON.Vector3.Zero();
  79577. this.xy = BABYLON.Vector3.Zero();
  79578. this.yz = BABYLON.Vector3.Zero();
  79579. this.zx = BABYLON.Vector3.Zero();
  79580. }
  79581. SphericalPolynomial.prototype.addAmbient = function (color) {
  79582. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79583. this.xx = this.xx.add(colorVector);
  79584. this.yy = this.yy.add(colorVector);
  79585. this.zz = this.zz.add(colorVector);
  79586. };
  79587. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79588. var result = new SphericalPolynomial();
  79589. result.x = harmonics.L11.scale(1.02333);
  79590. result.y = harmonics.L1_1.scale(1.02333);
  79591. result.z = harmonics.L10.scale(1.02333);
  79592. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79593. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79594. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79595. result.yz = harmonics.L2_1.scale(0.858086);
  79596. result.zx = harmonics.L21.scale(0.858086);
  79597. result.xy = harmonics.L2_2.scale(0.858086);
  79598. result.scale(1.0 / Math.PI);
  79599. return result;
  79600. };
  79601. SphericalPolynomial.prototype.scale = function (scale) {
  79602. this.x = this.x.scale(scale);
  79603. this.y = this.y.scale(scale);
  79604. this.z = this.z.scale(scale);
  79605. this.xx = this.xx.scale(scale);
  79606. this.yy = this.yy.scale(scale);
  79607. this.zz = this.zz.scale(scale);
  79608. this.yz = this.yz.scale(scale);
  79609. this.zx = this.zx.scale(scale);
  79610. this.xy = this.xy.scale(scale);
  79611. };
  79612. return SphericalPolynomial;
  79613. }());
  79614. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79615. var SphericalHarmonics = /** @class */ (function () {
  79616. function SphericalHarmonics() {
  79617. this.L00 = BABYLON.Vector3.Zero();
  79618. this.L1_1 = BABYLON.Vector3.Zero();
  79619. this.L10 = BABYLON.Vector3.Zero();
  79620. this.L11 = BABYLON.Vector3.Zero();
  79621. this.L2_2 = BABYLON.Vector3.Zero();
  79622. this.L2_1 = BABYLON.Vector3.Zero();
  79623. this.L20 = BABYLON.Vector3.Zero();
  79624. this.L21 = BABYLON.Vector3.Zero();
  79625. this.L22 = BABYLON.Vector3.Zero();
  79626. }
  79627. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79628. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79629. var c = colorVector.scale(deltaSolidAngle);
  79630. this.L00 = this.L00.add(c.scale(0.282095));
  79631. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79632. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79633. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79634. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79635. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79636. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79637. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79638. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79639. };
  79640. SphericalHarmonics.prototype.scale = function (scale) {
  79641. this.L00 = this.L00.scale(scale);
  79642. this.L1_1 = this.L1_1.scale(scale);
  79643. this.L10 = this.L10.scale(scale);
  79644. this.L11 = this.L11.scale(scale);
  79645. this.L2_2 = this.L2_2.scale(scale);
  79646. this.L2_1 = this.L2_1.scale(scale);
  79647. this.L20 = this.L20.scale(scale);
  79648. this.L21 = this.L21.scale(scale);
  79649. this.L22 = this.L22.scale(scale);
  79650. };
  79651. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79652. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79653. //
  79654. // E_lm = A_l * L_lm
  79655. //
  79656. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79657. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79658. // the scaling factors are given in equation 9.
  79659. // Constant (Band 0)
  79660. this.L00 = this.L00.scale(3.141593);
  79661. // Linear (Band 1)
  79662. this.L1_1 = this.L1_1.scale(2.094395);
  79663. this.L10 = this.L10.scale(2.094395);
  79664. this.L11 = this.L11.scale(2.094395);
  79665. // Quadratic (Band 2)
  79666. this.L2_2 = this.L2_2.scale(0.785398);
  79667. this.L2_1 = this.L2_1.scale(0.785398);
  79668. this.L20 = this.L20.scale(0.785398);
  79669. this.L21 = this.L21.scale(0.785398);
  79670. this.L22 = this.L22.scale(0.785398);
  79671. };
  79672. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79673. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79674. // L = (1/pi) * E * rho
  79675. //
  79676. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79677. this.scale(1.0 / Math.PI);
  79678. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79679. // (The pixel shader must apply albedo after texture fetches, etc).
  79680. };
  79681. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79682. var result = new SphericalHarmonics();
  79683. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79684. result.L1_1 = polynomial.y.scale(0.977204);
  79685. result.L10 = polynomial.z.scale(0.977204);
  79686. result.L11 = polynomial.x.scale(0.977204);
  79687. result.L2_2 = polynomial.xy.scale(1.16538);
  79688. result.L2_1 = polynomial.yz.scale(1.16538);
  79689. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79690. result.L21 = polynomial.zx.scale(1.16538);
  79691. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79692. result.scale(Math.PI);
  79693. return result;
  79694. };
  79695. return SphericalHarmonics;
  79696. }());
  79697. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79698. })(BABYLON || (BABYLON = {}));
  79699. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79700. var BABYLON;
  79701. (function (BABYLON) {
  79702. var FileFaceOrientation = /** @class */ (function () {
  79703. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79704. this.name = name;
  79705. this.worldAxisForNormal = worldAxisForNormal;
  79706. this.worldAxisForFileX = worldAxisForFileX;
  79707. this.worldAxisForFileY = worldAxisForFileY;
  79708. }
  79709. return FileFaceOrientation;
  79710. }());
  79711. ;
  79712. /**
  79713. * Helper class dealing with the extraction of spherical polynomial dataArray
  79714. * from a cube map.
  79715. */
  79716. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79717. function CubeMapToSphericalPolynomialTools() {
  79718. }
  79719. /**
  79720. * Converts a texture to the according Spherical Polynomial data.
  79721. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79722. *
  79723. * @param texture The texture to extract the information from.
  79724. * @return The Spherical Polynomial data.
  79725. */
  79726. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79727. if (!texture.isCube) {
  79728. // Only supports cube Textures currently.
  79729. return null;
  79730. }
  79731. var size = texture.getSize().width;
  79732. var right = texture.readPixels(0);
  79733. var left = texture.readPixels(1);
  79734. var up;
  79735. var down;
  79736. if (texture.isRenderTarget) {
  79737. up = texture.readPixels(3);
  79738. down = texture.readPixels(2);
  79739. }
  79740. else {
  79741. up = texture.readPixels(2);
  79742. down = texture.readPixels(3);
  79743. }
  79744. var front = texture.readPixels(4);
  79745. var back = texture.readPixels(5);
  79746. var gammaSpace = texture.gammaSpace;
  79747. // Always read as RGBA.
  79748. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79749. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79750. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79751. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79752. }
  79753. var cubeInfo = {
  79754. size: size,
  79755. right: right,
  79756. left: left,
  79757. up: up,
  79758. down: down,
  79759. front: front,
  79760. back: back,
  79761. format: format,
  79762. type: type,
  79763. gammaSpace: gammaSpace,
  79764. };
  79765. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79766. };
  79767. /**
  79768. * Converts a cubemap to the according Spherical Polynomial data.
  79769. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79770. *
  79771. * @param cubeInfo The Cube map to extract the information from.
  79772. * @return The Spherical Polynomial data.
  79773. */
  79774. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79775. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79776. var totalSolidAngle = 0.0;
  79777. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79778. var du = 2.0 / cubeInfo.size;
  79779. var dv = du;
  79780. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79781. var minUV = du * 0.5 - 1.0;
  79782. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79783. var fileFace = this.FileFaces[faceIndex];
  79784. var dataArray = cubeInfo[fileFace.name];
  79785. var v = minUV;
  79786. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79787. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79788. // Because SP is still linear, so summation is fine in that basis.
  79789. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79790. for (var y = 0; y < cubeInfo.size; y++) {
  79791. var u = minUV;
  79792. for (var x = 0; x < cubeInfo.size; x++) {
  79793. // World direction (not normalised)
  79794. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79795. worldDirection.normalize();
  79796. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79797. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79798. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79799. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79800. // Handle Integer types.
  79801. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79802. r /= 255;
  79803. g /= 255;
  79804. b /= 255;
  79805. }
  79806. // Handle Gamma space textures.
  79807. if (cubeInfo.gammaSpace) {
  79808. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79809. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79810. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79811. }
  79812. var color = new BABYLON.Color3(r, g, b);
  79813. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79814. totalSolidAngle += deltaSolidAngle;
  79815. u += du;
  79816. }
  79817. v += dv;
  79818. }
  79819. }
  79820. // Solid angle for entire sphere is 4*pi
  79821. var sphereSolidAngle = 4.0 * Math.PI;
  79822. // Adjust the solid angle to allow for how many faces we processed.
  79823. var facesProcessed = 6.0;
  79824. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79825. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79826. // This is needed because the numerical integration over the cube uses a
  79827. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79828. // and also to compensate for accumulative error due to float precision in the summation.
  79829. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79830. sphericalHarmonics.scale(correctionFactor);
  79831. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79832. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79833. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79834. };
  79835. CubeMapToSphericalPolynomialTools.FileFaces = [
  79836. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79837. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79838. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79839. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79840. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79841. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79842. ];
  79843. return CubeMapToSphericalPolynomialTools;
  79844. }());
  79845. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79846. })(BABYLON || (BABYLON = {}));
  79847. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79848. var BABYLON;
  79849. (function (BABYLON) {
  79850. /**
  79851. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79852. */
  79853. var PanoramaToCubeMapTools = /** @class */ (function () {
  79854. function PanoramaToCubeMapTools() {
  79855. }
  79856. /**
  79857. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79858. *
  79859. * @param float32Array The source data.
  79860. * @param inputWidth The width of the input panorama.
  79861. * @param inputhHeight The height of the input panorama.
  79862. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79863. * @return The cubemap data
  79864. */
  79865. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79866. if (!float32Array) {
  79867. throw "ConvertPanoramaToCubemap: input cannot be null";
  79868. }
  79869. if (float32Array.length != inputWidth * inputHeight * 3) {
  79870. throw "ConvertPanoramaToCubemap: input size is wrong";
  79871. }
  79872. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79873. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79874. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79875. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79876. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79877. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79878. return {
  79879. front: textureFront,
  79880. back: textureBack,
  79881. left: textureLeft,
  79882. right: textureRight,
  79883. up: textureUp,
  79884. down: textureDown,
  79885. size: size,
  79886. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79887. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79888. gammaSpace: false,
  79889. };
  79890. };
  79891. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79892. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79893. var textureArray = new Float32Array(buffer);
  79894. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79895. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79896. var dy = 1 / texSize;
  79897. var fy = 0;
  79898. for (var y = 0; y < texSize; y++) {
  79899. var xv1 = faceData[0];
  79900. var xv2 = faceData[2];
  79901. for (var x = 0; x < texSize; x++) {
  79902. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79903. v.normalize();
  79904. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79905. // 3 channels per pixels
  79906. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79907. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79908. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79909. xv1 = xv1.add(rotDX1);
  79910. xv2 = xv2.add(rotDX2);
  79911. }
  79912. fy += dy;
  79913. }
  79914. return textureArray;
  79915. };
  79916. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79917. var theta = Math.atan2(vDir.z, vDir.x);
  79918. var phi = Math.acos(vDir.y);
  79919. while (theta < -Math.PI)
  79920. theta += 2 * Math.PI;
  79921. while (theta > Math.PI)
  79922. theta -= 2 * Math.PI;
  79923. var dx = theta / Math.PI;
  79924. var dy = phi / Math.PI;
  79925. // recenter.
  79926. dx = dx * 0.5 + 0.5;
  79927. var px = Math.round(dx * inputWidth);
  79928. if (px < 0)
  79929. px = 0;
  79930. else if (px >= inputWidth)
  79931. px = inputWidth - 1;
  79932. var py = Math.round(dy * inputHeight);
  79933. if (py < 0)
  79934. py = 0;
  79935. else if (py >= inputHeight)
  79936. py = inputHeight - 1;
  79937. var inputY = (inputHeight - py - 1);
  79938. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79939. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79940. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79941. return {
  79942. r: r,
  79943. g: g,
  79944. b: b
  79945. };
  79946. };
  79947. PanoramaToCubeMapTools.FACE_FRONT = [
  79948. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79949. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79950. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79951. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79952. ];
  79953. PanoramaToCubeMapTools.FACE_BACK = [
  79954. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79955. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79956. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79957. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79958. ];
  79959. PanoramaToCubeMapTools.FACE_RIGHT = [
  79960. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79961. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79962. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79963. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79964. ];
  79965. PanoramaToCubeMapTools.FACE_LEFT = [
  79966. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79967. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79968. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79969. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79970. ];
  79971. PanoramaToCubeMapTools.FACE_DOWN = [
  79972. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79973. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79974. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79975. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79976. ];
  79977. PanoramaToCubeMapTools.FACE_UP = [
  79978. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79979. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79980. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79981. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79982. ];
  79983. return PanoramaToCubeMapTools;
  79984. }());
  79985. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79986. })(BABYLON || (BABYLON = {}));
  79987. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79988. var BABYLON;
  79989. (function (BABYLON) {
  79990. ;
  79991. /**
  79992. * This groups tools to convert HDR texture to native colors array.
  79993. */
  79994. var HDRTools = /** @class */ (function () {
  79995. function HDRTools() {
  79996. }
  79997. HDRTools.Ldexp = function (mantissa, exponent) {
  79998. if (exponent > 1023) {
  79999. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80000. }
  80001. if (exponent < -1074) {
  80002. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80003. }
  80004. return mantissa * Math.pow(2, exponent);
  80005. };
  80006. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80007. if (exponent > 0) { /*nonzero pixel*/
  80008. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80009. float32array[index + 0] = red * exponent;
  80010. float32array[index + 1] = green * exponent;
  80011. float32array[index + 2] = blue * exponent;
  80012. }
  80013. else {
  80014. float32array[index + 0] = 0;
  80015. float32array[index + 1] = 0;
  80016. float32array[index + 2] = 0;
  80017. }
  80018. };
  80019. HDRTools.readStringLine = function (uint8array, startIndex) {
  80020. var line = "";
  80021. var character = "";
  80022. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80023. character = String.fromCharCode(uint8array[i]);
  80024. if (character == "\n") {
  80025. break;
  80026. }
  80027. line += character;
  80028. }
  80029. return line;
  80030. };
  80031. /**
  80032. * Reads header information from an RGBE texture stored in a native array.
  80033. * More information on this format are available here:
  80034. * https://en.wikipedia.org/wiki/RGBE_image_format
  80035. *
  80036. * @param uint8array The binary file stored in native array.
  80037. * @return The header information.
  80038. */
  80039. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80040. var height = 0;
  80041. var width = 0;
  80042. var line = this.readStringLine(uint8array, 0);
  80043. if (line[0] != '#' || line[1] != '?') {
  80044. throw "Bad HDR Format.";
  80045. }
  80046. var endOfHeader = false;
  80047. var findFormat = false;
  80048. var lineIndex = 0;
  80049. do {
  80050. lineIndex += (line.length + 1);
  80051. line = this.readStringLine(uint8array, lineIndex);
  80052. if (line == "FORMAT=32-bit_rle_rgbe") {
  80053. findFormat = true;
  80054. }
  80055. else if (line.length == 0) {
  80056. endOfHeader = true;
  80057. }
  80058. } while (!endOfHeader);
  80059. if (!findFormat) {
  80060. throw "HDR Bad header format, unsupported FORMAT";
  80061. }
  80062. lineIndex += (line.length + 1);
  80063. line = this.readStringLine(uint8array, lineIndex);
  80064. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80065. var match = sizeRegexp.exec(line);
  80066. // TODO. Support +Y and -X if needed.
  80067. if (!match || match.length < 3) {
  80068. throw "HDR Bad header format, no size";
  80069. }
  80070. width = parseInt(match[2]);
  80071. height = parseInt(match[1]);
  80072. if (width < 8 || width > 0x7fff) {
  80073. throw "HDR Bad header format, unsupported size";
  80074. }
  80075. lineIndex += (line.length + 1);
  80076. return {
  80077. height: height,
  80078. width: width,
  80079. dataPosition: lineIndex
  80080. };
  80081. };
  80082. /**
  80083. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80084. * This RGBE texture needs to store the information as a panorama.
  80085. *
  80086. * More information on this format are available here:
  80087. * https://en.wikipedia.org/wiki/RGBE_image_format
  80088. *
  80089. * @param buffer The binary file stored in an array buffer.
  80090. * @param size The expected size of the extracted cubemap.
  80091. * @return The Cube Map information.
  80092. */
  80093. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80094. var uint8array = new Uint8Array(buffer);
  80095. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80096. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80097. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80098. return cubeMapData;
  80099. };
  80100. /**
  80101. * Returns the pixels data extracted from an RGBE texture.
  80102. * This pixels will be stored left to right up to down in the R G B order in one array.
  80103. *
  80104. * More information on this format are available here:
  80105. * https://en.wikipedia.org/wiki/RGBE_image_format
  80106. *
  80107. * @param uint8array The binary file stored in an array buffer.
  80108. * @param hdrInfo The header information of the file.
  80109. * @return The pixels data in RGB right to left up to down order.
  80110. */
  80111. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80112. // Keep for multi format supports.
  80113. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80114. };
  80115. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80116. var num_scanlines = hdrInfo.height;
  80117. var scanline_width = hdrInfo.width;
  80118. var a, b, c, d, count;
  80119. var dataIndex = hdrInfo.dataPosition;
  80120. var index = 0, endIndex = 0, i = 0;
  80121. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80122. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80123. // 3 channels of 4 bytes per pixel in float.
  80124. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80125. var resultArray = new Float32Array(resultBuffer);
  80126. // read in each successive scanline
  80127. while (num_scanlines > 0) {
  80128. a = uint8array[dataIndex++];
  80129. b = uint8array[dataIndex++];
  80130. c = uint8array[dataIndex++];
  80131. d = uint8array[dataIndex++];
  80132. if (a != 2 || b != 2 || (c & 0x80)) {
  80133. // this file is not run length encoded
  80134. throw "HDR Bad header format, not RLE";
  80135. }
  80136. if (((c << 8) | d) != scanline_width) {
  80137. throw "HDR Bad header format, wrong scan line width";
  80138. }
  80139. index = 0;
  80140. // read each of the four channels for the scanline into the buffer
  80141. for (i = 0; i < 4; i++) {
  80142. endIndex = (i + 1) * scanline_width;
  80143. while (index < endIndex) {
  80144. a = uint8array[dataIndex++];
  80145. b = uint8array[dataIndex++];
  80146. if (a > 128) {
  80147. // a run of the same value
  80148. count = a - 128;
  80149. if ((count == 0) || (count > endIndex - index)) {
  80150. throw "HDR Bad Format, bad scanline data (run)";
  80151. }
  80152. while (count-- > 0) {
  80153. scanLineArray[index++] = b;
  80154. }
  80155. }
  80156. else {
  80157. // a non-run
  80158. count = a;
  80159. if ((count == 0) || (count > endIndex - index)) {
  80160. throw "HDR Bad Format, bad scanline data (non-run)";
  80161. }
  80162. scanLineArray[index++] = b;
  80163. if (--count > 0) {
  80164. for (var j = 0; j < count; j++) {
  80165. scanLineArray[index++] = uint8array[dataIndex++];
  80166. }
  80167. }
  80168. }
  80169. }
  80170. }
  80171. // now convert data from buffer into floats
  80172. for (i = 0; i < scanline_width; i++) {
  80173. a = scanLineArray[i];
  80174. b = scanLineArray[i + scanline_width];
  80175. c = scanLineArray[i + 2 * scanline_width];
  80176. d = scanLineArray[i + 3 * scanline_width];
  80177. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80178. }
  80179. num_scanlines--;
  80180. }
  80181. return resultArray;
  80182. };
  80183. return HDRTools;
  80184. }());
  80185. BABYLON.HDRTools = HDRTools;
  80186. })(BABYLON || (BABYLON = {}));
  80187. //# sourceMappingURL=babylon.hdr.js.map
  80188. var BABYLON;
  80189. (function (BABYLON) {
  80190. /**
  80191. * This represents a texture coming from an HDR input.
  80192. *
  80193. * The only supported format is currently panorama picture stored in RGBE format.
  80194. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80195. */
  80196. var HDRCubeTexture = /** @class */ (function (_super) {
  80197. __extends(HDRCubeTexture, _super);
  80198. /**
  80199. * Instantiates an HDRTexture from the following parameters.
  80200. *
  80201. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80202. * @param scene The scene the texture will be used in
  80203. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80204. * @param noMipmap Forces to not generate the mipmap if true
  80205. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80206. * @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)
  80207. * @param reserved Reserved flag for internal use.
  80208. */
  80209. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80210. if (noMipmap === void 0) { noMipmap = false; }
  80211. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80212. if (gammaSpace === void 0) { gammaSpace = false; }
  80213. if (reserved === void 0) { reserved = false; }
  80214. if (onLoad === void 0) { onLoad = null; }
  80215. if (onError === void 0) { onError = null; }
  80216. var _this = _super.call(this, scene) || this;
  80217. _this._generateHarmonics = true;
  80218. _this._onLoad = null;
  80219. _this._onError = null;
  80220. /**
  80221. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80222. */
  80223. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80224. _this._isBlocking = true;
  80225. _this._rotationY = 0;
  80226. /**
  80227. * Gets or sets the center of the bounding box associated with the cube texture
  80228. * It must define where the camera used to render the texture was set
  80229. */
  80230. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80231. if (!url) {
  80232. return _this;
  80233. }
  80234. _this.name = url;
  80235. _this.url = url;
  80236. _this.hasAlpha = false;
  80237. _this.isCube = true;
  80238. _this._textureMatrix = BABYLON.Matrix.Identity();
  80239. _this._onLoad = onLoad;
  80240. _this._onError = onError;
  80241. _this.gammaSpace = gammaSpace;
  80242. _this._noMipmap = noMipmap;
  80243. _this._size = size;
  80244. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80245. if (!_this._texture) {
  80246. if (!scene.useDelayedTextureLoading) {
  80247. _this.loadTexture();
  80248. }
  80249. else {
  80250. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80251. }
  80252. }
  80253. return _this;
  80254. }
  80255. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80256. /**
  80257. * Gets wether or not the texture is blocking during loading.
  80258. */
  80259. get: function () {
  80260. return this._isBlocking;
  80261. },
  80262. /**
  80263. * Sets wether or not the texture is blocking during loading.
  80264. */
  80265. set: function (value) {
  80266. this._isBlocking = value;
  80267. },
  80268. enumerable: true,
  80269. configurable: true
  80270. });
  80271. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80272. /**
  80273. * Gets texture matrix rotation angle around Y axis radians.
  80274. */
  80275. get: function () {
  80276. return this._rotationY;
  80277. },
  80278. /**
  80279. * Sets texture matrix rotation angle around Y axis in radians.
  80280. */
  80281. set: function (value) {
  80282. this._rotationY = value;
  80283. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80284. },
  80285. enumerable: true,
  80286. configurable: true
  80287. });
  80288. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80289. get: function () {
  80290. return this._boundingBoxSize;
  80291. },
  80292. /**
  80293. * Gets or sets the size of the bounding box associated with the cube texture
  80294. * When defined, the cubemap will switch to local mode
  80295. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80296. * @example https://www.babylonjs-playground.com/#RNASML
  80297. */
  80298. set: function (value) {
  80299. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80300. return;
  80301. }
  80302. this._boundingBoxSize = value;
  80303. var scene = this.getScene();
  80304. if (scene) {
  80305. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80306. }
  80307. },
  80308. enumerable: true,
  80309. configurable: true
  80310. });
  80311. /**
  80312. * Occurs when the file is raw .hdr file.
  80313. */
  80314. HDRCubeTexture.prototype.loadTexture = function () {
  80315. var _this = this;
  80316. var callback = function (buffer) {
  80317. var scene = _this.getScene();
  80318. if (!scene) {
  80319. return null;
  80320. }
  80321. // Extract the raw linear data.
  80322. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80323. // Generate harmonics if needed.
  80324. if (_this._generateHarmonics) {
  80325. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80326. _this.sphericalPolynomial = sphericalPolynomial;
  80327. }
  80328. var results = [];
  80329. var byteArray = null;
  80330. // Push each faces.
  80331. for (var j = 0; j < 6; j++) {
  80332. // Create uintarray fallback.
  80333. if (!scene.getEngine().getCaps().textureFloat) {
  80334. // 3 channels of 1 bytes per pixel in bytes.
  80335. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80336. byteArray = new Uint8Array(byteBuffer);
  80337. }
  80338. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80339. // If special cases.
  80340. if (_this.gammaSpace || byteArray) {
  80341. for (var i = 0; i < _this._size * _this._size; i++) {
  80342. // Put in gamma space if requested.
  80343. if (_this.gammaSpace) {
  80344. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80345. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80346. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80347. }
  80348. // Convert to int texture for fallback.
  80349. if (byteArray) {
  80350. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80351. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80352. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80353. // May use luminance instead if the result is not accurate.
  80354. var max = Math.max(Math.max(r, g), b);
  80355. if (max > 255) {
  80356. var scale = 255 / max;
  80357. r *= scale;
  80358. g *= scale;
  80359. b *= scale;
  80360. }
  80361. byteArray[(i * 3) + 0] = r;
  80362. byteArray[(i * 3) + 1] = g;
  80363. byteArray[(i * 3) + 2] = b;
  80364. }
  80365. }
  80366. }
  80367. if (byteArray) {
  80368. results.push(byteArray);
  80369. }
  80370. else {
  80371. results.push(dataFace);
  80372. }
  80373. }
  80374. return results;
  80375. };
  80376. var scene = this.getScene();
  80377. if (scene) {
  80378. 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);
  80379. }
  80380. };
  80381. HDRCubeTexture.prototype.clone = function () {
  80382. var scene = this.getScene();
  80383. if (!scene) {
  80384. return this;
  80385. }
  80386. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80387. // Base texture
  80388. newTexture.level = this.level;
  80389. newTexture.wrapU = this.wrapU;
  80390. newTexture.wrapV = this.wrapV;
  80391. newTexture.coordinatesIndex = this.coordinatesIndex;
  80392. newTexture.coordinatesMode = this.coordinatesMode;
  80393. return newTexture;
  80394. };
  80395. // Methods
  80396. HDRCubeTexture.prototype.delayLoad = function () {
  80397. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80398. return;
  80399. }
  80400. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80401. this._texture = this._getFromCache(this.url, this._noMipmap);
  80402. if (!this._texture) {
  80403. this.loadTexture();
  80404. }
  80405. };
  80406. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80407. return this._textureMatrix;
  80408. };
  80409. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80410. this._textureMatrix = value;
  80411. };
  80412. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80413. var texture = null;
  80414. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80415. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80416. texture.name = parsedTexture.name;
  80417. texture.hasAlpha = parsedTexture.hasAlpha;
  80418. texture.level = parsedTexture.level;
  80419. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80420. texture.isBlocking = parsedTexture.isBlocking;
  80421. }
  80422. if (texture) {
  80423. if (parsedTexture.boundingBoxPosition) {
  80424. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80425. }
  80426. if (parsedTexture.boundingBoxSize) {
  80427. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80428. }
  80429. if (parsedTexture.rotationY) {
  80430. texture.rotationY = parsedTexture.rotationY;
  80431. }
  80432. }
  80433. return texture;
  80434. };
  80435. HDRCubeTexture.prototype.serialize = function () {
  80436. if (!this.name) {
  80437. return null;
  80438. }
  80439. var serializationObject = {};
  80440. serializationObject.name = this.name;
  80441. serializationObject.hasAlpha = this.hasAlpha;
  80442. serializationObject.isCube = true;
  80443. serializationObject.level = this.level;
  80444. serializationObject.size = this._size;
  80445. serializationObject.coordinatesMode = this.coordinatesMode;
  80446. serializationObject.useInGammaSpace = this.gammaSpace;
  80447. serializationObject.generateHarmonics = this._generateHarmonics;
  80448. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80449. serializationObject.noMipmap = this._noMipmap;
  80450. serializationObject.isBlocking = this._isBlocking;
  80451. serializationObject.rotationY = this._rotationY;
  80452. return serializationObject;
  80453. };
  80454. HDRCubeTexture._facesMapping = [
  80455. "right",
  80456. "left",
  80457. "up",
  80458. "down",
  80459. "front",
  80460. "back"
  80461. ];
  80462. return HDRCubeTexture;
  80463. }(BABYLON.BaseTexture));
  80464. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80465. })(BABYLON || (BABYLON = {}));
  80466. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80467. var BABYLON;
  80468. (function (BABYLON) {
  80469. var IndexedVector2 = /** @class */ (function (_super) {
  80470. __extends(IndexedVector2, _super);
  80471. function IndexedVector2(original, index) {
  80472. var _this = _super.call(this, original.x, original.y) || this;
  80473. _this.index = index;
  80474. return _this;
  80475. }
  80476. return IndexedVector2;
  80477. }(BABYLON.Vector2));
  80478. var PolygonPoints = /** @class */ (function () {
  80479. function PolygonPoints() {
  80480. this.elements = new Array();
  80481. }
  80482. PolygonPoints.prototype.add = function (originalPoints) {
  80483. var _this = this;
  80484. var result = new Array();
  80485. originalPoints.forEach(function (point) {
  80486. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80487. var newPoint = new IndexedVector2(point, _this.elements.length);
  80488. result.push(newPoint);
  80489. _this.elements.push(newPoint);
  80490. }
  80491. });
  80492. return result;
  80493. };
  80494. PolygonPoints.prototype.computeBounds = function () {
  80495. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80496. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80497. this.elements.forEach(function (point) {
  80498. // x
  80499. if (point.x < lmin.x) {
  80500. lmin.x = point.x;
  80501. }
  80502. else if (point.x > lmax.x) {
  80503. lmax.x = point.x;
  80504. }
  80505. // y
  80506. if (point.y < lmin.y) {
  80507. lmin.y = point.y;
  80508. }
  80509. else if (point.y > lmax.y) {
  80510. lmax.y = point.y;
  80511. }
  80512. });
  80513. return {
  80514. min: lmin,
  80515. max: lmax,
  80516. width: lmax.x - lmin.x,
  80517. height: lmax.y - lmin.y
  80518. };
  80519. };
  80520. return PolygonPoints;
  80521. }());
  80522. var Polygon = /** @class */ (function () {
  80523. function Polygon() {
  80524. }
  80525. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80526. return [
  80527. new BABYLON.Vector2(xmin, ymin),
  80528. new BABYLON.Vector2(xmax, ymin),
  80529. new BABYLON.Vector2(xmax, ymax),
  80530. new BABYLON.Vector2(xmin, ymax)
  80531. ];
  80532. };
  80533. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80534. if (cx === void 0) { cx = 0; }
  80535. if (cy === void 0) { cy = 0; }
  80536. if (numberOfSides === void 0) { numberOfSides = 32; }
  80537. var result = new Array();
  80538. var angle = 0;
  80539. var increment = (Math.PI * 2) / numberOfSides;
  80540. for (var i = 0; i < numberOfSides; i++) {
  80541. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80542. angle -= increment;
  80543. }
  80544. return result;
  80545. };
  80546. Polygon.Parse = function (input) {
  80547. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80548. var i, result = [];
  80549. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80550. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80551. }
  80552. return result;
  80553. };
  80554. Polygon.StartingAt = function (x, y) {
  80555. return BABYLON.Path2.StartingAt(x, y);
  80556. };
  80557. return Polygon;
  80558. }());
  80559. BABYLON.Polygon = Polygon;
  80560. var PolygonMeshBuilder = /** @class */ (function () {
  80561. function PolygonMeshBuilder(name, contours, scene) {
  80562. this._points = new PolygonPoints();
  80563. this._outlinepoints = new PolygonPoints();
  80564. this._holes = new Array();
  80565. this._epoints = new Array();
  80566. this._eholes = new Array();
  80567. this._name = name;
  80568. this._scene = scene;
  80569. var points;
  80570. if (contours instanceof BABYLON.Path2) {
  80571. points = contours.getPoints();
  80572. }
  80573. else {
  80574. points = contours;
  80575. }
  80576. this._addToepoint(points);
  80577. this._points.add(points);
  80578. this._outlinepoints.add(points);
  80579. if (typeof earcut === 'undefined') {
  80580. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80581. }
  80582. }
  80583. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80584. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80585. var p = points_1[_i];
  80586. this._epoints.push(p.x, p.y);
  80587. }
  80588. };
  80589. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80590. this._points.add(hole);
  80591. var holepoints = new PolygonPoints();
  80592. holepoints.add(hole);
  80593. this._holes.push(holepoints);
  80594. this._eholes.push(this._epoints.length / 2);
  80595. this._addToepoint(hole);
  80596. return this;
  80597. };
  80598. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80599. var _this = this;
  80600. if (updatable === void 0) { updatable = false; }
  80601. if (depth === void 0) { depth = 0; }
  80602. var result = new BABYLON.Mesh(this._name, this._scene);
  80603. var normals = new Array();
  80604. var positions = new Array();
  80605. var uvs = new Array();
  80606. var bounds = this._points.computeBounds();
  80607. this._points.elements.forEach(function (p) {
  80608. normals.push(0, 1.0, 0);
  80609. positions.push(p.x, 0, p.y);
  80610. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80611. });
  80612. var indices = new Array();
  80613. var res = earcut(this._epoints, this._eholes, 2);
  80614. for (var i = 0; i < res.length; i++) {
  80615. indices.push(res[i]);
  80616. }
  80617. if (depth > 0) {
  80618. var positionscount = (positions.length / 3); //get the current pointcount
  80619. this._points.elements.forEach(function (p) {
  80620. normals.push(0, -1.0, 0);
  80621. positions.push(p.x, -depth, p.y);
  80622. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80623. });
  80624. var totalCount = indices.length;
  80625. for (var i = 0; i < totalCount; i += 3) {
  80626. var i0 = indices[i + 0];
  80627. var i1 = indices[i + 1];
  80628. var i2 = indices[i + 2];
  80629. indices.push(i2 + positionscount);
  80630. indices.push(i1 + positionscount);
  80631. indices.push(i0 + positionscount);
  80632. }
  80633. //Add the sides
  80634. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80635. this._holes.forEach(function (hole) {
  80636. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80637. });
  80638. }
  80639. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80640. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80641. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80642. result.setIndices(indices);
  80643. return result;
  80644. };
  80645. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80646. var StartIndex = positions.length / 3;
  80647. var ulength = 0;
  80648. for (var i = 0; i < points.elements.length; i++) {
  80649. var p = points.elements[i];
  80650. var p1;
  80651. if ((i + 1) > points.elements.length - 1) {
  80652. p1 = points.elements[0];
  80653. }
  80654. else {
  80655. p1 = points.elements[i + 1];
  80656. }
  80657. positions.push(p.x, 0, p.y);
  80658. positions.push(p.x, -depth, p.y);
  80659. positions.push(p1.x, 0, p1.y);
  80660. positions.push(p1.x, -depth, p1.y);
  80661. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80662. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80663. var v3 = v2.subtract(v1);
  80664. var v4 = new BABYLON.Vector3(0, 1, 0);
  80665. var vn = BABYLON.Vector3.Cross(v3, v4);
  80666. vn = vn.normalize();
  80667. uvs.push(ulength / bounds.width, 0);
  80668. uvs.push(ulength / bounds.width, 1);
  80669. ulength += v3.length();
  80670. uvs.push((ulength / bounds.width), 0);
  80671. uvs.push((ulength / bounds.width), 1);
  80672. if (!flip) {
  80673. normals.push(-vn.x, -vn.y, -vn.z);
  80674. normals.push(-vn.x, -vn.y, -vn.z);
  80675. normals.push(-vn.x, -vn.y, -vn.z);
  80676. normals.push(-vn.x, -vn.y, -vn.z);
  80677. indices.push(StartIndex);
  80678. indices.push(StartIndex + 1);
  80679. indices.push(StartIndex + 2);
  80680. indices.push(StartIndex + 1);
  80681. indices.push(StartIndex + 3);
  80682. indices.push(StartIndex + 2);
  80683. }
  80684. else {
  80685. normals.push(vn.x, vn.y, vn.z);
  80686. normals.push(vn.x, vn.y, vn.z);
  80687. normals.push(vn.x, vn.y, vn.z);
  80688. normals.push(vn.x, vn.y, vn.z);
  80689. indices.push(StartIndex);
  80690. indices.push(StartIndex + 2);
  80691. indices.push(StartIndex + 1);
  80692. indices.push(StartIndex + 1);
  80693. indices.push(StartIndex + 2);
  80694. indices.push(StartIndex + 3);
  80695. }
  80696. StartIndex += 4;
  80697. }
  80698. ;
  80699. };
  80700. return PolygonMeshBuilder;
  80701. }());
  80702. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80703. })(BABYLON || (BABYLON = {}));
  80704. //# sourceMappingURL=babylon.polygonMesh.js.map
  80705. var BABYLON;
  80706. (function (BABYLON) {
  80707. // Unique ID when we import meshes from Babylon to CSG
  80708. var currentCSGMeshId = 0;
  80709. // # class Vertex
  80710. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80711. // one to provide additional features like texture coordinates and vertex
  80712. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80713. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80714. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80715. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80716. // is not used anywhere else.
  80717. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80718. var Vertex = /** @class */ (function () {
  80719. function Vertex(pos, normal, uv) {
  80720. this.pos = pos;
  80721. this.normal = normal;
  80722. this.uv = uv;
  80723. }
  80724. Vertex.prototype.clone = function () {
  80725. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80726. };
  80727. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80728. // orientation of a polygon is flipped.
  80729. Vertex.prototype.flip = function () {
  80730. this.normal = this.normal.scale(-1);
  80731. };
  80732. // Create a new vertex between this vertex and `other` by linearly
  80733. // interpolating all properties using a parameter of `t`. Subclasses should
  80734. // override this to interpolate additional properties.
  80735. Vertex.prototype.interpolate = function (other, t) {
  80736. 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));
  80737. };
  80738. return Vertex;
  80739. }());
  80740. // # class Plane
  80741. // Represents a plane in 3D space.
  80742. var Plane = /** @class */ (function () {
  80743. function Plane(normal, w) {
  80744. this.normal = normal;
  80745. this.w = w;
  80746. }
  80747. Plane.FromPoints = function (a, b, c) {
  80748. var v0 = c.subtract(a);
  80749. var v1 = b.subtract(a);
  80750. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80751. return null;
  80752. }
  80753. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80754. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80755. };
  80756. Plane.prototype.clone = function () {
  80757. return new Plane(this.normal.clone(), this.w);
  80758. };
  80759. Plane.prototype.flip = function () {
  80760. this.normal.scaleInPlace(-1);
  80761. this.w = -this.w;
  80762. };
  80763. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80764. // fragments in the appropriate lists. Coplanar polygons go into either
  80765. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80766. // respect to this plane. Polygons in front or in back of this plane go into
  80767. // either `front` or `back`.
  80768. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80769. var COPLANAR = 0;
  80770. var FRONT = 1;
  80771. var BACK = 2;
  80772. var SPANNING = 3;
  80773. // Classify each point as well as the entire polygon into one of the above
  80774. // four classes.
  80775. var polygonType = 0;
  80776. var types = [];
  80777. var i;
  80778. var t;
  80779. for (i = 0; i < polygon.vertices.length; i++) {
  80780. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80781. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80782. polygonType |= type;
  80783. types.push(type);
  80784. }
  80785. // Put the polygon in the correct list, splitting it when necessary.
  80786. switch (polygonType) {
  80787. case COPLANAR:
  80788. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80789. break;
  80790. case FRONT:
  80791. front.push(polygon);
  80792. break;
  80793. case BACK:
  80794. back.push(polygon);
  80795. break;
  80796. case SPANNING:
  80797. var f = [], b = [];
  80798. for (i = 0; i < polygon.vertices.length; i++) {
  80799. var j = (i + 1) % polygon.vertices.length;
  80800. var ti = types[i], tj = types[j];
  80801. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80802. if (ti !== BACK)
  80803. f.push(vi);
  80804. if (ti !== FRONT)
  80805. b.push(ti !== BACK ? vi.clone() : vi);
  80806. if ((ti | tj) === SPANNING) {
  80807. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80808. var v = vi.interpolate(vj, t);
  80809. f.push(v);
  80810. b.push(v.clone());
  80811. }
  80812. }
  80813. var poly;
  80814. if (f.length >= 3) {
  80815. poly = new Polygon(f, polygon.shared);
  80816. if (poly.plane)
  80817. front.push(poly);
  80818. }
  80819. if (b.length >= 3) {
  80820. poly = new Polygon(b, polygon.shared);
  80821. if (poly.plane)
  80822. back.push(poly);
  80823. }
  80824. break;
  80825. }
  80826. };
  80827. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80828. // point is on the plane.
  80829. Plane.EPSILON = 1e-5;
  80830. return Plane;
  80831. }());
  80832. // # class Polygon
  80833. // Represents a convex polygon. The vertices used to initialize a polygon must
  80834. // be coplanar and form a convex loop.
  80835. //
  80836. // Each convex polygon has a `shared` property, which is shared between all
  80837. // polygons that are clones of each other or were split from the same polygon.
  80838. // This can be used to define per-polygon properties (such as surface color).
  80839. var Polygon = /** @class */ (function () {
  80840. function Polygon(vertices, shared) {
  80841. this.vertices = vertices;
  80842. this.shared = shared;
  80843. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80844. }
  80845. Polygon.prototype.clone = function () {
  80846. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80847. return new Polygon(vertices, this.shared);
  80848. };
  80849. Polygon.prototype.flip = function () {
  80850. this.vertices.reverse().map(function (v) { v.flip(); });
  80851. this.plane.flip();
  80852. };
  80853. return Polygon;
  80854. }());
  80855. // # class Node
  80856. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80857. // by picking a polygon to split along. That polygon (and all other coplanar
  80858. // polygons) are added directly to that node and the other polygons are added to
  80859. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80860. // no distinction between internal and leaf nodes.
  80861. var Node = /** @class */ (function () {
  80862. function Node(polygons) {
  80863. this.plane = null;
  80864. this.front = null;
  80865. this.back = null;
  80866. this.polygons = new Array();
  80867. if (polygons) {
  80868. this.build(polygons);
  80869. }
  80870. }
  80871. Node.prototype.clone = function () {
  80872. var node = new Node();
  80873. node.plane = this.plane && this.plane.clone();
  80874. node.front = this.front && this.front.clone();
  80875. node.back = this.back && this.back.clone();
  80876. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80877. return node;
  80878. };
  80879. // Convert solid space to empty space and empty space to solid space.
  80880. Node.prototype.invert = function () {
  80881. for (var i = 0; i < this.polygons.length; i++) {
  80882. this.polygons[i].flip();
  80883. }
  80884. if (this.plane) {
  80885. this.plane.flip();
  80886. }
  80887. if (this.front) {
  80888. this.front.invert();
  80889. }
  80890. if (this.back) {
  80891. this.back.invert();
  80892. }
  80893. var temp = this.front;
  80894. this.front = this.back;
  80895. this.back = temp;
  80896. };
  80897. // Recursively remove all polygons in `polygons` that are inside this BSP
  80898. // tree.
  80899. Node.prototype.clipPolygons = function (polygons) {
  80900. if (!this.plane)
  80901. return polygons.slice();
  80902. var front = new Array(), back = new Array();
  80903. for (var i = 0; i < polygons.length; i++) {
  80904. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80905. }
  80906. if (this.front) {
  80907. front = this.front.clipPolygons(front);
  80908. }
  80909. if (this.back) {
  80910. back = this.back.clipPolygons(back);
  80911. }
  80912. else {
  80913. back = [];
  80914. }
  80915. return front.concat(back);
  80916. };
  80917. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80918. // `bsp`.
  80919. Node.prototype.clipTo = function (bsp) {
  80920. this.polygons = bsp.clipPolygons(this.polygons);
  80921. if (this.front)
  80922. this.front.clipTo(bsp);
  80923. if (this.back)
  80924. this.back.clipTo(bsp);
  80925. };
  80926. // Return a list of all polygons in this BSP tree.
  80927. Node.prototype.allPolygons = function () {
  80928. var polygons = this.polygons.slice();
  80929. if (this.front)
  80930. polygons = polygons.concat(this.front.allPolygons());
  80931. if (this.back)
  80932. polygons = polygons.concat(this.back.allPolygons());
  80933. return polygons;
  80934. };
  80935. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80936. // new polygons are filtered down to the bottom of the tree and become new
  80937. // nodes there. Each set of polygons is partitioned using the first polygon
  80938. // (no heuristic is used to pick a good split).
  80939. Node.prototype.build = function (polygons) {
  80940. if (!polygons.length)
  80941. return;
  80942. if (!this.plane)
  80943. this.plane = polygons[0].plane.clone();
  80944. var front = new Array(), back = new Array();
  80945. for (var i = 0; i < polygons.length; i++) {
  80946. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80947. }
  80948. if (front.length) {
  80949. if (!this.front)
  80950. this.front = new Node();
  80951. this.front.build(front);
  80952. }
  80953. if (back.length) {
  80954. if (!this.back)
  80955. this.back = new Node();
  80956. this.back.build(back);
  80957. }
  80958. };
  80959. return Node;
  80960. }());
  80961. var CSG = /** @class */ (function () {
  80962. function CSG() {
  80963. this.polygons = new Array();
  80964. }
  80965. // Convert BABYLON.Mesh to BABYLON.CSG
  80966. CSG.FromMesh = function (mesh) {
  80967. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80968. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80969. if (mesh instanceof BABYLON.Mesh) {
  80970. mesh.computeWorldMatrix(true);
  80971. matrix = mesh.getWorldMatrix();
  80972. meshPosition = mesh.position.clone();
  80973. meshRotation = mesh.rotation.clone();
  80974. if (mesh.rotationQuaternion) {
  80975. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80976. }
  80977. meshScaling = mesh.scaling.clone();
  80978. }
  80979. else {
  80980. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80981. }
  80982. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80983. var subMeshes = mesh.subMeshes;
  80984. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80985. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80986. vertices = [];
  80987. for (var j = 0; j < 3; j++) {
  80988. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80989. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80990. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80991. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80992. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80993. vertex = new Vertex(position, normal, uv);
  80994. vertices.push(vertex);
  80995. }
  80996. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80997. // To handle the case of degenerated triangle
  80998. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80999. if (polygon.plane)
  81000. polygons.push(polygon);
  81001. }
  81002. }
  81003. var csg = CSG.FromPolygons(polygons);
  81004. csg.matrix = matrix;
  81005. csg.position = meshPosition;
  81006. csg.rotation = meshRotation;
  81007. csg.scaling = meshScaling;
  81008. csg.rotationQuaternion = meshRotationQuaternion;
  81009. currentCSGMeshId++;
  81010. return csg;
  81011. };
  81012. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81013. CSG.FromPolygons = function (polygons) {
  81014. var csg = new CSG();
  81015. csg.polygons = polygons;
  81016. return csg;
  81017. };
  81018. CSG.prototype.clone = function () {
  81019. var csg = new CSG();
  81020. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81021. csg.copyTransformAttributes(this);
  81022. return csg;
  81023. };
  81024. CSG.prototype.union = function (csg) {
  81025. var a = new Node(this.clone().polygons);
  81026. var b = new Node(csg.clone().polygons);
  81027. a.clipTo(b);
  81028. b.clipTo(a);
  81029. b.invert();
  81030. b.clipTo(a);
  81031. b.invert();
  81032. a.build(b.allPolygons());
  81033. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81034. };
  81035. CSG.prototype.unionInPlace = function (csg) {
  81036. var a = new Node(this.polygons);
  81037. var b = new Node(csg.polygons);
  81038. a.clipTo(b);
  81039. b.clipTo(a);
  81040. b.invert();
  81041. b.clipTo(a);
  81042. b.invert();
  81043. a.build(b.allPolygons());
  81044. this.polygons = a.allPolygons();
  81045. };
  81046. CSG.prototype.subtract = function (csg) {
  81047. var a = new Node(this.clone().polygons);
  81048. var b = new Node(csg.clone().polygons);
  81049. a.invert();
  81050. a.clipTo(b);
  81051. b.clipTo(a);
  81052. b.invert();
  81053. b.clipTo(a);
  81054. b.invert();
  81055. a.build(b.allPolygons());
  81056. a.invert();
  81057. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81058. };
  81059. CSG.prototype.subtractInPlace = function (csg) {
  81060. var a = new Node(this.polygons);
  81061. var b = new Node(csg.polygons);
  81062. a.invert();
  81063. a.clipTo(b);
  81064. b.clipTo(a);
  81065. b.invert();
  81066. b.clipTo(a);
  81067. b.invert();
  81068. a.build(b.allPolygons());
  81069. a.invert();
  81070. this.polygons = a.allPolygons();
  81071. };
  81072. CSG.prototype.intersect = function (csg) {
  81073. var a = new Node(this.clone().polygons);
  81074. var b = new Node(csg.clone().polygons);
  81075. a.invert();
  81076. b.clipTo(a);
  81077. b.invert();
  81078. a.clipTo(b);
  81079. b.clipTo(a);
  81080. a.build(b.allPolygons());
  81081. a.invert();
  81082. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81083. };
  81084. CSG.prototype.intersectInPlace = function (csg) {
  81085. var a = new Node(this.polygons);
  81086. var b = new Node(csg.polygons);
  81087. a.invert();
  81088. b.clipTo(a);
  81089. b.invert();
  81090. a.clipTo(b);
  81091. b.clipTo(a);
  81092. a.build(b.allPolygons());
  81093. a.invert();
  81094. this.polygons = a.allPolygons();
  81095. };
  81096. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81097. // not modified.
  81098. CSG.prototype.inverse = function () {
  81099. var csg = this.clone();
  81100. csg.inverseInPlace();
  81101. return csg;
  81102. };
  81103. CSG.prototype.inverseInPlace = function () {
  81104. this.polygons.map(function (p) { p.flip(); });
  81105. };
  81106. // This is used to keep meshes transformations so they can be restored
  81107. // when we build back a Babylon Mesh
  81108. // NB : All CSG operations are performed in world coordinates
  81109. CSG.prototype.copyTransformAttributes = function (csg) {
  81110. this.matrix = csg.matrix;
  81111. this.position = csg.position;
  81112. this.rotation = csg.rotation;
  81113. this.scaling = csg.scaling;
  81114. this.rotationQuaternion = csg.rotationQuaternion;
  81115. return this;
  81116. };
  81117. // Build Raw mesh from CSG
  81118. // Coordinates here are in world space
  81119. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81120. var matrix = this.matrix.clone();
  81121. matrix.invert();
  81122. 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;
  81123. if (keepSubMeshes) {
  81124. // Sort Polygons, since subMeshes are indices range
  81125. polygons.sort(function (a, b) {
  81126. if (a.shared.meshId === b.shared.meshId) {
  81127. return a.shared.subMeshId - b.shared.subMeshId;
  81128. }
  81129. else {
  81130. return a.shared.meshId - b.shared.meshId;
  81131. }
  81132. });
  81133. }
  81134. for (var i = 0, il = polygons.length; i < il; i++) {
  81135. polygon = polygons[i];
  81136. // Building SubMeshes
  81137. if (!subMesh_dict[polygon.shared.meshId]) {
  81138. subMesh_dict[polygon.shared.meshId] = {};
  81139. }
  81140. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81141. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81142. indexStart: +Infinity,
  81143. indexEnd: -Infinity,
  81144. materialIndex: polygon.shared.materialIndex
  81145. };
  81146. }
  81147. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81148. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81149. polygonIndices[0] = 0;
  81150. polygonIndices[1] = j - 1;
  81151. polygonIndices[2] = j;
  81152. for (var k = 0; k < 3; k++) {
  81153. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81154. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81155. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81156. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81157. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81158. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81159. // Check if 2 points can be merged
  81160. if (!(typeof vertex_idx !== 'undefined' &&
  81161. normals[vertex_idx * 3] === localNormal.x &&
  81162. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81163. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81164. uvs[vertex_idx * 2] === uv.x &&
  81165. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81166. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81167. uvs.push(uv.x, uv.y);
  81168. normals.push(normal.x, normal.y, normal.z);
  81169. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81170. }
  81171. indices.push(vertex_idx);
  81172. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81173. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81174. currentIndex++;
  81175. }
  81176. }
  81177. }
  81178. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81179. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81180. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81181. mesh.setIndices(indices, null);
  81182. if (keepSubMeshes) {
  81183. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81184. var materialIndexOffset = 0, materialMaxIndex;
  81185. mesh.subMeshes = new Array();
  81186. for (var m in subMesh_dict) {
  81187. materialMaxIndex = -1;
  81188. for (var sm in subMesh_dict[m]) {
  81189. subMesh_obj = subMesh_dict[m][sm];
  81190. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81191. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81192. }
  81193. materialIndexOffset += ++materialMaxIndex;
  81194. }
  81195. }
  81196. return mesh;
  81197. };
  81198. // Build Mesh from CSG taking material and transforms into account
  81199. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81200. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81201. mesh.material = material;
  81202. mesh.position.copyFrom(this.position);
  81203. mesh.rotation.copyFrom(this.rotation);
  81204. if (this.rotationQuaternion) {
  81205. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81206. }
  81207. mesh.scaling.copyFrom(this.scaling);
  81208. mesh.computeWorldMatrix(true);
  81209. return mesh;
  81210. };
  81211. return CSG;
  81212. }());
  81213. BABYLON.CSG = CSG;
  81214. })(BABYLON || (BABYLON = {}));
  81215. //# sourceMappingURL=babylon.csg.js.map
  81216. var BABYLON;
  81217. (function (BABYLON) {
  81218. var LensFlare = /** @class */ (function () {
  81219. function LensFlare(size, position, color, imgUrl, system) {
  81220. this.size = size;
  81221. this.position = position;
  81222. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81223. this.color = color || new BABYLON.Color3(1, 1, 1);
  81224. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81225. this._system = system;
  81226. system.lensFlares.push(this);
  81227. }
  81228. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81229. return new LensFlare(size, position, color, imgUrl, system);
  81230. };
  81231. LensFlare.prototype.dispose = function () {
  81232. if (this.texture) {
  81233. this.texture.dispose();
  81234. }
  81235. // Remove from scene
  81236. var index = this._system.lensFlares.indexOf(this);
  81237. this._system.lensFlares.splice(index, 1);
  81238. };
  81239. ;
  81240. return LensFlare;
  81241. }());
  81242. BABYLON.LensFlare = LensFlare;
  81243. })(BABYLON || (BABYLON = {}));
  81244. //# sourceMappingURL=babylon.lensFlare.js.map
  81245. var BABYLON;
  81246. (function (BABYLON) {
  81247. var LensFlareSystem = /** @class */ (function () {
  81248. function LensFlareSystem(name, emitter, scene) {
  81249. this.name = name;
  81250. this.lensFlares = new Array();
  81251. this.borderLimit = 300;
  81252. this.viewportBorder = 0;
  81253. this.layerMask = 0x0FFFFFFF;
  81254. this._vertexBuffers = {};
  81255. this._isEnabled = true;
  81256. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81257. this._emitter = emitter;
  81258. this.id = name;
  81259. scene.lensFlareSystems.push(this);
  81260. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81261. var engine = scene.getEngine();
  81262. // VBO
  81263. var vertices = [];
  81264. vertices.push(1, 1);
  81265. vertices.push(-1, 1);
  81266. vertices.push(-1, -1);
  81267. vertices.push(1, -1);
  81268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81269. // Indices
  81270. var indices = [];
  81271. indices.push(0);
  81272. indices.push(1);
  81273. indices.push(2);
  81274. indices.push(0);
  81275. indices.push(2);
  81276. indices.push(3);
  81277. this._indexBuffer = engine.createIndexBuffer(indices);
  81278. // Effects
  81279. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81280. }
  81281. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81282. get: function () {
  81283. return this._isEnabled;
  81284. },
  81285. set: function (value) {
  81286. this._isEnabled = value;
  81287. },
  81288. enumerable: true,
  81289. configurable: true
  81290. });
  81291. LensFlareSystem.prototype.getScene = function () {
  81292. return this._scene;
  81293. };
  81294. LensFlareSystem.prototype.getEmitter = function () {
  81295. return this._emitter;
  81296. };
  81297. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81298. this._emitter = newEmitter;
  81299. };
  81300. LensFlareSystem.prototype.getEmitterPosition = function () {
  81301. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81302. };
  81303. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81304. var position = this.getEmitterPosition();
  81305. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81306. this._positionX = position.x;
  81307. this._positionY = position.y;
  81308. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81309. if (this.viewportBorder > 0) {
  81310. globalViewport.x -= this.viewportBorder;
  81311. globalViewport.y -= this.viewportBorder;
  81312. globalViewport.width += this.viewportBorder * 2;
  81313. globalViewport.height += this.viewportBorder * 2;
  81314. position.x += this.viewportBorder;
  81315. position.y += this.viewportBorder;
  81316. this._positionX += this.viewportBorder;
  81317. this._positionY += this.viewportBorder;
  81318. }
  81319. if (position.z > 0) {
  81320. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81321. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81322. return true;
  81323. }
  81324. return true;
  81325. }
  81326. return false;
  81327. };
  81328. LensFlareSystem.prototype._isVisible = function () {
  81329. if (!this._isEnabled || !this._scene.activeCamera) {
  81330. return false;
  81331. }
  81332. var emitterPosition = this.getEmitterPosition();
  81333. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81334. var distance = direction.length();
  81335. direction.normalize();
  81336. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81337. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81338. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81339. };
  81340. LensFlareSystem.prototype.render = function () {
  81341. if (!this._effect.isReady() || !this._scene.activeCamera)
  81342. return false;
  81343. var engine = this._scene.getEngine();
  81344. var viewport = this._scene.activeCamera.viewport;
  81345. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81346. // Position
  81347. if (!this.computeEffectivePosition(globalViewport)) {
  81348. return false;
  81349. }
  81350. // Visibility
  81351. if (!this._isVisible()) {
  81352. return false;
  81353. }
  81354. // Intensity
  81355. var awayX;
  81356. var awayY;
  81357. if (this._positionX < this.borderLimit + globalViewport.x) {
  81358. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81359. }
  81360. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81361. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81362. }
  81363. else {
  81364. awayX = 0;
  81365. }
  81366. if (this._positionY < this.borderLimit + globalViewport.y) {
  81367. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81368. }
  81369. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81370. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81371. }
  81372. else {
  81373. awayY = 0;
  81374. }
  81375. var away = (awayX > awayY) ? awayX : awayY;
  81376. away -= this.viewportBorder;
  81377. if (away > this.borderLimit) {
  81378. away = this.borderLimit;
  81379. }
  81380. var intensity = 1.0 - (away / this.borderLimit);
  81381. if (intensity < 0) {
  81382. return false;
  81383. }
  81384. if (intensity > 1.0) {
  81385. intensity = 1.0;
  81386. }
  81387. if (this.viewportBorder > 0) {
  81388. globalViewport.x += this.viewportBorder;
  81389. globalViewport.y += this.viewportBorder;
  81390. globalViewport.width -= this.viewportBorder * 2;
  81391. globalViewport.height -= this.viewportBorder * 2;
  81392. this._positionX -= this.viewportBorder;
  81393. this._positionY -= this.viewportBorder;
  81394. }
  81395. // Position
  81396. var centerX = globalViewport.x + globalViewport.width / 2;
  81397. var centerY = globalViewport.y + globalViewport.height / 2;
  81398. var distX = centerX - this._positionX;
  81399. var distY = centerY - this._positionY;
  81400. // Effects
  81401. engine.enableEffect(this._effect);
  81402. engine.setState(false);
  81403. engine.setDepthBuffer(false);
  81404. // VBOs
  81405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81406. // Flares
  81407. for (var index = 0; index < this.lensFlares.length; index++) {
  81408. var flare = this.lensFlares[index];
  81409. engine.setAlphaMode(flare.alphaMode);
  81410. var x = centerX - (distX * flare.position);
  81411. var y = centerY - (distY * flare.position);
  81412. var cw = flare.size;
  81413. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81414. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81415. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81416. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81417. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81418. // Texture
  81419. this._effect.setTexture("textureSampler", flare.texture);
  81420. // Color
  81421. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81422. // Draw order
  81423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81424. }
  81425. engine.setDepthBuffer(true);
  81426. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81427. return true;
  81428. };
  81429. LensFlareSystem.prototype.dispose = function () {
  81430. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81431. if (vertexBuffer) {
  81432. vertexBuffer.dispose();
  81433. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81434. }
  81435. if (this._indexBuffer) {
  81436. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81437. this._indexBuffer = null;
  81438. }
  81439. while (this.lensFlares.length) {
  81440. this.lensFlares[0].dispose();
  81441. }
  81442. // Remove from scene
  81443. var index = this._scene.lensFlareSystems.indexOf(this);
  81444. this._scene.lensFlareSystems.splice(index, 1);
  81445. };
  81446. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81447. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81448. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81449. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81450. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81451. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81452. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81453. var parsedFlare = parsedLensFlareSystem.flares[index];
  81454. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81455. }
  81456. return lensFlareSystem;
  81457. };
  81458. LensFlareSystem.prototype.serialize = function () {
  81459. var serializationObject = {};
  81460. serializationObject.id = this.id;
  81461. serializationObject.name = this.name;
  81462. serializationObject.emitterId = this.getEmitter().id;
  81463. serializationObject.borderLimit = this.borderLimit;
  81464. serializationObject.flares = [];
  81465. for (var index = 0; index < this.lensFlares.length; index++) {
  81466. var flare = this.lensFlares[index];
  81467. serializationObject.flares.push({
  81468. size: flare.size,
  81469. position: flare.position,
  81470. color: flare.color.asArray(),
  81471. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81472. });
  81473. }
  81474. return serializationObject;
  81475. };
  81476. return LensFlareSystem;
  81477. }());
  81478. BABYLON.LensFlareSystem = LensFlareSystem;
  81479. })(BABYLON || (BABYLON = {}));
  81480. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81481. var BABYLON;
  81482. (function (BABYLON) {
  81483. /**
  81484. * This is a holder class for the physics joint created by the physics plugin.
  81485. * It holds a set of functions to control the underlying joint.
  81486. */
  81487. var PhysicsJoint = /** @class */ (function () {
  81488. function PhysicsJoint(type, jointData) {
  81489. this.type = type;
  81490. this.jointData = jointData;
  81491. jointData.nativeParams = jointData.nativeParams || {};
  81492. }
  81493. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81494. get: function () {
  81495. return this._physicsJoint;
  81496. },
  81497. set: function (newJoint) {
  81498. if (this._physicsJoint) {
  81499. //remove from the wolrd
  81500. }
  81501. this._physicsJoint = newJoint;
  81502. },
  81503. enumerable: true,
  81504. configurable: true
  81505. });
  81506. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81507. set: function (physicsPlugin) {
  81508. this._physicsPlugin = physicsPlugin;
  81509. },
  81510. enumerable: true,
  81511. configurable: true
  81512. });
  81513. /**
  81514. * Execute a function that is physics-plugin specific.
  81515. * @param {Function} func the function that will be executed.
  81516. * It accepts two parameters: the physics world and the physics joint.
  81517. */
  81518. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81519. func(this._physicsPlugin.world, this._physicsJoint);
  81520. };
  81521. //TODO check if the native joints are the same
  81522. //Joint Types
  81523. PhysicsJoint.DistanceJoint = 0;
  81524. PhysicsJoint.HingeJoint = 1;
  81525. PhysicsJoint.BallAndSocketJoint = 2;
  81526. PhysicsJoint.WheelJoint = 3;
  81527. PhysicsJoint.SliderJoint = 4;
  81528. //OIMO
  81529. PhysicsJoint.PrismaticJoint = 5;
  81530. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81531. PhysicsJoint.UniversalJoint = 6;
  81532. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81533. //Cannon
  81534. //Similar to a Ball-Joint. Different in params
  81535. PhysicsJoint.PointToPointJoint = 8;
  81536. //Cannon only at the moment
  81537. PhysicsJoint.SpringJoint = 9;
  81538. PhysicsJoint.LockJoint = 10;
  81539. return PhysicsJoint;
  81540. }());
  81541. BABYLON.PhysicsJoint = PhysicsJoint;
  81542. /**
  81543. * A class representing a physics distance joint.
  81544. */
  81545. var DistanceJoint = /** @class */ (function (_super) {
  81546. __extends(DistanceJoint, _super);
  81547. function DistanceJoint(jointData) {
  81548. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81549. }
  81550. /**
  81551. * Update the predefined distance.
  81552. */
  81553. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81554. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81555. };
  81556. return DistanceJoint;
  81557. }(PhysicsJoint));
  81558. BABYLON.DistanceJoint = DistanceJoint;
  81559. var MotorEnabledJoint = /** @class */ (function (_super) {
  81560. __extends(MotorEnabledJoint, _super);
  81561. function MotorEnabledJoint(type, jointData) {
  81562. return _super.call(this, type, jointData) || this;
  81563. }
  81564. /**
  81565. * Set the motor values.
  81566. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81567. * @param {number} force the force to apply
  81568. * @param {number} maxForce max force for this motor.
  81569. */
  81570. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81571. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81572. };
  81573. /**
  81574. * Set the motor's limits.
  81575. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81576. */
  81577. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81578. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81579. };
  81580. return MotorEnabledJoint;
  81581. }(PhysicsJoint));
  81582. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81583. /**
  81584. * This class represents a single hinge physics joint
  81585. */
  81586. var HingeJoint = /** @class */ (function (_super) {
  81587. __extends(HingeJoint, _super);
  81588. function HingeJoint(jointData) {
  81589. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81590. }
  81591. /**
  81592. * Set the motor values.
  81593. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81594. * @param {number} force the force to apply
  81595. * @param {number} maxForce max force for this motor.
  81596. */
  81597. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81598. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81599. };
  81600. /**
  81601. * Set the motor's limits.
  81602. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81603. */
  81604. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81605. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81606. };
  81607. return HingeJoint;
  81608. }(MotorEnabledJoint));
  81609. BABYLON.HingeJoint = HingeJoint;
  81610. /**
  81611. * This class represents a dual hinge physics joint (same as wheel joint)
  81612. */
  81613. var Hinge2Joint = /** @class */ (function (_super) {
  81614. __extends(Hinge2Joint, _super);
  81615. function Hinge2Joint(jointData) {
  81616. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81617. }
  81618. /**
  81619. * Set the motor values.
  81620. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81621. * @param {number} force the force to apply
  81622. * @param {number} maxForce max force for this motor.
  81623. * @param {motorIndex} the motor's index, 0 or 1.
  81624. */
  81625. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81626. if (motorIndex === void 0) { motorIndex = 0; }
  81627. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81628. };
  81629. /**
  81630. * Set the motor limits.
  81631. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81632. * @param {number} upperLimit the upper limit
  81633. * @param {number} lowerLimit lower limit
  81634. * @param {motorIndex} the motor's index, 0 or 1.
  81635. */
  81636. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81637. if (motorIndex === void 0) { motorIndex = 0; }
  81638. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81639. };
  81640. return Hinge2Joint;
  81641. }(MotorEnabledJoint));
  81642. BABYLON.Hinge2Joint = Hinge2Joint;
  81643. })(BABYLON || (BABYLON = {}));
  81644. //# sourceMappingURL=babylon.physicsJoint.js.map
  81645. var BABYLON;
  81646. (function (BABYLON) {
  81647. var PhysicsImpostor = /** @class */ (function () {
  81648. function PhysicsImpostor(object, type, _options, _scene) {
  81649. if (_options === void 0) { _options = { mass: 0 }; }
  81650. var _this = this;
  81651. this.object = object;
  81652. this.type = type;
  81653. this._options = _options;
  81654. this._scene = _scene;
  81655. this._bodyUpdateRequired = false;
  81656. this._onBeforePhysicsStepCallbacks = new Array();
  81657. this._onAfterPhysicsStepCallbacks = new Array();
  81658. this._onPhysicsCollideCallbacks = [];
  81659. this._deltaPosition = BABYLON.Vector3.Zero();
  81660. this._isDisposed = false;
  81661. //temp variables for parent rotation calculations
  81662. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81663. this._tmpQuat = new BABYLON.Quaternion();
  81664. this._tmpQuat2 = new BABYLON.Quaternion();
  81665. /**
  81666. * this function is executed by the physics engine.
  81667. */
  81668. this.beforeStep = function () {
  81669. if (!_this._physicsEngine) {
  81670. return;
  81671. }
  81672. _this.object.translate(_this._deltaPosition, -1);
  81673. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81674. _this.object.computeWorldMatrix(false);
  81675. if (_this.object.parent && _this.object.rotationQuaternion) {
  81676. _this.getParentsRotation();
  81677. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81678. }
  81679. else {
  81680. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81681. }
  81682. if (!_this._options.disableBidirectionalTransformation) {
  81683. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81684. }
  81685. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81686. func(_this);
  81687. });
  81688. };
  81689. /**
  81690. * this function is executed by the physics engine.
  81691. */
  81692. this.afterStep = function () {
  81693. if (!_this._physicsEngine) {
  81694. return;
  81695. }
  81696. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81697. func(_this);
  81698. });
  81699. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81700. // object has now its world rotation. needs to be converted to local.
  81701. if (_this.object.parent && _this.object.rotationQuaternion) {
  81702. _this.getParentsRotation();
  81703. _this._tmpQuat.conjugateInPlace();
  81704. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81705. }
  81706. // take the position set and make it the absolute position of this object.
  81707. _this.object.setAbsolutePosition(_this.object.position);
  81708. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81709. _this.object.translate(_this._deltaPosition, 1);
  81710. };
  81711. /**
  81712. * Legacy collision detection event support
  81713. */
  81714. this.onCollideEvent = null;
  81715. //event and body object due to cannon's event-based architecture.
  81716. this.onCollide = function (e) {
  81717. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81718. return;
  81719. }
  81720. if (!_this._physicsEngine) {
  81721. return;
  81722. }
  81723. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81724. if (otherImpostor) {
  81725. // Legacy collision detection event support
  81726. if (_this.onCollideEvent) {
  81727. _this.onCollideEvent(_this, otherImpostor);
  81728. }
  81729. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81730. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81731. }).forEach(function (obj) {
  81732. obj.callback(_this, otherImpostor);
  81733. });
  81734. }
  81735. };
  81736. //sanity check!
  81737. if (!this.object) {
  81738. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81739. return;
  81740. }
  81741. //legacy support for old syntax.
  81742. if (!this._scene && object.getScene) {
  81743. this._scene = object.getScene();
  81744. }
  81745. if (!this._scene) {
  81746. return;
  81747. }
  81748. this._physicsEngine = this._scene.getPhysicsEngine();
  81749. if (!this._physicsEngine) {
  81750. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81751. }
  81752. else {
  81753. //set the object's quaternion, if not set
  81754. if (!this.object.rotationQuaternion) {
  81755. if (this.object.rotation) {
  81756. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81757. }
  81758. else {
  81759. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81760. }
  81761. }
  81762. //default options params
  81763. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81764. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81765. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81766. this._joints = [];
  81767. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81768. if (!this.object.parent || this._options.ignoreParent) {
  81769. this._init();
  81770. }
  81771. else if (this.object.parent.physicsImpostor) {
  81772. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81773. }
  81774. }
  81775. }
  81776. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81777. get: function () {
  81778. return this._isDisposed;
  81779. },
  81780. enumerable: true,
  81781. configurable: true
  81782. });
  81783. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81784. get: function () {
  81785. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81786. },
  81787. set: function (value) {
  81788. this.setMass(value);
  81789. },
  81790. enumerable: true,
  81791. configurable: true
  81792. });
  81793. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81794. get: function () {
  81795. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81796. },
  81797. set: function (value) {
  81798. if (!this._physicsEngine) {
  81799. return;
  81800. }
  81801. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81802. },
  81803. enumerable: true,
  81804. configurable: true
  81805. });
  81806. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81807. get: function () {
  81808. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81809. },
  81810. set: function (value) {
  81811. if (!this._physicsEngine) {
  81812. return;
  81813. }
  81814. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81815. },
  81816. enumerable: true,
  81817. configurable: true
  81818. });
  81819. /**
  81820. * This function will completly initialize this impostor.
  81821. * It will create a new body - but only if this mesh has no parent.
  81822. * If it has, this impostor will not be used other than to define the impostor
  81823. * of the child mesh.
  81824. */
  81825. PhysicsImpostor.prototype._init = function () {
  81826. if (!this._physicsEngine) {
  81827. return;
  81828. }
  81829. this._physicsEngine.removeImpostor(this);
  81830. this.physicsBody = null;
  81831. this._parent = this._parent || this._getPhysicsParent();
  81832. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81833. this._physicsEngine.addImpostor(this);
  81834. }
  81835. };
  81836. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81837. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81838. var parentMesh = this.object.parent;
  81839. return parentMesh.physicsImpostor;
  81840. }
  81841. return null;
  81842. };
  81843. /**
  81844. * Should a new body be generated.
  81845. */
  81846. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81847. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81848. };
  81849. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81850. this.forceUpdate();
  81851. };
  81852. /**
  81853. * Force a regeneration of this or the parent's impostor's body.
  81854. * Use under cautious - This will remove all joints already implemented.
  81855. */
  81856. PhysicsImpostor.prototype.forceUpdate = function () {
  81857. this._init();
  81858. if (this.parent && !this._options.ignoreParent) {
  81859. this.parent.forceUpdate();
  81860. }
  81861. };
  81862. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81863. /*public get mesh(): AbstractMesh {
  81864. return this._mesh;
  81865. }*/
  81866. /**
  81867. * Gets the body that holds this impostor. Either its own, or its parent.
  81868. */
  81869. get: function () {
  81870. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81871. },
  81872. /**
  81873. * Set the physics body. Used mainly by the physics engine/plugin
  81874. */
  81875. set: function (physicsBody) {
  81876. if (this._physicsBody && this._physicsEngine) {
  81877. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81878. }
  81879. this._physicsBody = physicsBody;
  81880. this.resetUpdateFlags();
  81881. },
  81882. enumerable: true,
  81883. configurable: true
  81884. });
  81885. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81886. get: function () {
  81887. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81888. },
  81889. set: function (value) {
  81890. this._parent = value;
  81891. },
  81892. enumerable: true,
  81893. configurable: true
  81894. });
  81895. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81896. this._bodyUpdateRequired = false;
  81897. };
  81898. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81899. if (this.object.getBoundingInfo) {
  81900. var q = this.object.rotationQuaternion;
  81901. //reset rotation
  81902. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81903. //calculate the world matrix with no rotation
  81904. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81905. var boundingInfo = this.object.getBoundingInfo();
  81906. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81907. //bring back the rotation
  81908. this.object.rotationQuaternion = q;
  81909. //calculate the world matrix with the new rotation
  81910. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81911. return size;
  81912. }
  81913. else {
  81914. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81915. }
  81916. };
  81917. PhysicsImpostor.prototype.getObjectCenter = function () {
  81918. if (this.object.getBoundingInfo) {
  81919. var boundingInfo = this.object.getBoundingInfo();
  81920. return boundingInfo.boundingBox.centerWorld;
  81921. }
  81922. else {
  81923. return this.object.position;
  81924. }
  81925. };
  81926. /**
  81927. * Get a specific parametes from the options parameter.
  81928. */
  81929. PhysicsImpostor.prototype.getParam = function (paramName) {
  81930. return this._options[paramName];
  81931. };
  81932. /**
  81933. * Sets a specific parameter in the options given to the physics plugin
  81934. */
  81935. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81936. this._options[paramName] = value;
  81937. this._bodyUpdateRequired = true;
  81938. };
  81939. /**
  81940. * Specifically change the body's mass option. Won't recreate the physics body object
  81941. */
  81942. PhysicsImpostor.prototype.setMass = function (mass) {
  81943. if (this.getParam("mass") !== mass) {
  81944. this.setParam("mass", mass);
  81945. }
  81946. if (this._physicsEngine) {
  81947. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81948. }
  81949. };
  81950. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81951. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81952. };
  81953. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81954. if (this._physicsEngine) {
  81955. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81956. }
  81957. };
  81958. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81959. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81960. };
  81961. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81962. if (this._physicsEngine) {
  81963. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81964. }
  81965. };
  81966. /**
  81967. * Execute a function with the physics plugin native code.
  81968. * Provide a function the will have two variables - the world object and the physics body object.
  81969. */
  81970. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81971. if (this._physicsEngine) {
  81972. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81973. }
  81974. };
  81975. /**
  81976. * Register a function that will be executed before the physics world is stepping forward.
  81977. */
  81978. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81979. this._onBeforePhysicsStepCallbacks.push(func);
  81980. };
  81981. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81982. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81983. if (index > -1) {
  81984. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81985. }
  81986. else {
  81987. BABYLON.Tools.Warn("Function to remove was not found");
  81988. }
  81989. };
  81990. /**
  81991. * Register a function that will be executed after the physics step
  81992. */
  81993. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81994. this._onAfterPhysicsStepCallbacks.push(func);
  81995. };
  81996. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81997. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81998. if (index > -1) {
  81999. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82000. }
  82001. else {
  82002. BABYLON.Tools.Warn("Function to remove was not found");
  82003. }
  82004. };
  82005. /**
  82006. * register a function that will be executed when this impostor collides against a different body.
  82007. */
  82008. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82009. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82010. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82011. };
  82012. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82013. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82014. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82015. if (index > -1) {
  82016. this._onPhysicsCollideCallbacks.splice(index, 1);
  82017. }
  82018. else {
  82019. BABYLON.Tools.Warn("Function to remove was not found");
  82020. }
  82021. };
  82022. PhysicsImpostor.prototype.getParentsRotation = function () {
  82023. var parent = this.object.parent;
  82024. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82025. while (parent) {
  82026. if (parent.rotationQuaternion) {
  82027. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82028. }
  82029. else {
  82030. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82031. }
  82032. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82033. parent = parent.parent;
  82034. }
  82035. return this._tmpQuat;
  82036. };
  82037. /**
  82038. * Apply a force
  82039. */
  82040. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82041. if (this._physicsEngine) {
  82042. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82043. }
  82044. return this;
  82045. };
  82046. /**
  82047. * Apply an impulse
  82048. */
  82049. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82050. if (this._physicsEngine) {
  82051. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82052. }
  82053. return this;
  82054. };
  82055. /**
  82056. * A help function to create a joint.
  82057. */
  82058. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82059. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82060. this.addJoint(otherImpostor, joint);
  82061. return this;
  82062. };
  82063. /**
  82064. * Add a joint to this impostor with a different impostor.
  82065. */
  82066. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82067. this._joints.push({
  82068. otherImpostor: otherImpostor,
  82069. joint: joint
  82070. });
  82071. if (this._physicsEngine) {
  82072. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82073. }
  82074. return this;
  82075. };
  82076. /**
  82077. * Will keep this body still, in a sleep mode.
  82078. */
  82079. PhysicsImpostor.prototype.sleep = function () {
  82080. if (this._physicsEngine) {
  82081. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82082. }
  82083. return this;
  82084. };
  82085. /**
  82086. * Wake the body up.
  82087. */
  82088. PhysicsImpostor.prototype.wakeUp = function () {
  82089. if (this._physicsEngine) {
  82090. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82091. }
  82092. return this;
  82093. };
  82094. PhysicsImpostor.prototype.clone = function (newObject) {
  82095. if (!newObject)
  82096. return null;
  82097. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82098. };
  82099. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82100. var _this = this;
  82101. //no dispose if no physics engine is available.
  82102. if (!this._physicsEngine) {
  82103. return;
  82104. }
  82105. this._joints.forEach(function (j) {
  82106. if (_this._physicsEngine) {
  82107. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82108. }
  82109. });
  82110. //dispose the physics body
  82111. this._physicsEngine.removeImpostor(this);
  82112. if (this.parent) {
  82113. this.parent.forceUpdate();
  82114. }
  82115. else {
  82116. /*this._object.getChildMeshes().forEach(function(mesh) {
  82117. if (mesh.physicsImpostor) {
  82118. if (disposeChildren) {
  82119. mesh.physicsImpostor.dispose();
  82120. mesh.physicsImpostor = null;
  82121. }
  82122. }
  82123. })*/
  82124. }
  82125. this._isDisposed = true;
  82126. };
  82127. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82128. this._deltaPosition.copyFrom(position);
  82129. };
  82130. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82131. if (!this._deltaRotation) {
  82132. this._deltaRotation = new BABYLON.Quaternion();
  82133. }
  82134. this._deltaRotation.copyFrom(rotation);
  82135. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82136. };
  82137. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82138. if (this._physicsEngine) {
  82139. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82140. }
  82141. return this;
  82142. };
  82143. PhysicsImpostor.prototype.getRadius = function () {
  82144. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82145. };
  82146. /**
  82147. * Sync a bone with this impostor
  82148. * @param bone The bone to sync to the impostor.
  82149. * @param boneMesh The mesh that the bone is influencing.
  82150. * @param jointPivot The pivot of the joint / bone in local space.
  82151. * @param distToJoint Optional distance from the impostor to the joint.
  82152. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82153. */
  82154. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82155. var tempVec = PhysicsImpostor._tmpVecs[0];
  82156. var mesh = this.object;
  82157. if (mesh.rotationQuaternion) {
  82158. if (adjustRotation) {
  82159. var tempQuat = PhysicsImpostor._tmpQuat;
  82160. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82161. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82162. }
  82163. else {
  82164. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82165. }
  82166. }
  82167. tempVec.x = 0;
  82168. tempVec.y = 0;
  82169. tempVec.z = 0;
  82170. if (jointPivot) {
  82171. tempVec.x = jointPivot.x;
  82172. tempVec.y = jointPivot.y;
  82173. tempVec.z = jointPivot.z;
  82174. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82175. if (distToJoint === undefined || distToJoint === null) {
  82176. distToJoint = jointPivot.length();
  82177. }
  82178. tempVec.x *= distToJoint;
  82179. tempVec.y *= distToJoint;
  82180. tempVec.z *= distToJoint;
  82181. }
  82182. if (bone.getParent()) {
  82183. tempVec.addInPlace(mesh.getAbsolutePosition());
  82184. bone.setAbsolutePosition(tempVec, boneMesh);
  82185. }
  82186. else {
  82187. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82188. boneMesh.position.x -= tempVec.x;
  82189. boneMesh.position.y -= tempVec.y;
  82190. boneMesh.position.z -= tempVec.z;
  82191. }
  82192. };
  82193. /**
  82194. * Sync impostor to a bone
  82195. * @param bone The bone that the impostor will be synced to.
  82196. * @param boneMesh The mesh that the bone is influencing.
  82197. * @param jointPivot The pivot of the joint / bone in local space.
  82198. * @param distToJoint Optional distance from the impostor to the joint.
  82199. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82200. * @param boneAxis Optional vector3 axis the bone is aligned with
  82201. */
  82202. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82203. var mesh = this.object;
  82204. if (mesh.rotationQuaternion) {
  82205. if (adjustRotation) {
  82206. var tempQuat = PhysicsImpostor._tmpQuat;
  82207. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82208. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82209. }
  82210. else {
  82211. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82212. }
  82213. }
  82214. var pos = PhysicsImpostor._tmpVecs[0];
  82215. var boneDir = PhysicsImpostor._tmpVecs[1];
  82216. if (!boneAxis) {
  82217. boneAxis = PhysicsImpostor._tmpVecs[2];
  82218. boneAxis.x = 0;
  82219. boneAxis.y = 1;
  82220. boneAxis.z = 0;
  82221. }
  82222. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82223. bone.getAbsolutePositionToRef(boneMesh, pos);
  82224. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82225. distToJoint = jointPivot.length();
  82226. }
  82227. if (distToJoint !== undefined && distToJoint !== null) {
  82228. pos.x += boneDir.x * distToJoint;
  82229. pos.y += boneDir.y * distToJoint;
  82230. pos.z += boneDir.z * distToJoint;
  82231. }
  82232. mesh.setAbsolutePosition(pos);
  82233. };
  82234. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82235. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82236. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82237. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82238. //Impostor types
  82239. PhysicsImpostor.NoImpostor = 0;
  82240. PhysicsImpostor.SphereImpostor = 1;
  82241. PhysicsImpostor.BoxImpostor = 2;
  82242. PhysicsImpostor.PlaneImpostor = 3;
  82243. PhysicsImpostor.MeshImpostor = 4;
  82244. PhysicsImpostor.CylinderImpostor = 7;
  82245. PhysicsImpostor.ParticleImpostor = 8;
  82246. PhysicsImpostor.HeightmapImpostor = 9;
  82247. return PhysicsImpostor;
  82248. }());
  82249. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82250. })(BABYLON || (BABYLON = {}));
  82251. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82252. var BABYLON;
  82253. (function (BABYLON) {
  82254. var PhysicsEngine = /** @class */ (function () {
  82255. function PhysicsEngine(gravity, _physicsPlugin) {
  82256. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82257. this._physicsPlugin = _physicsPlugin;
  82258. //new methods and parameters
  82259. this._impostors = [];
  82260. this._joints = [];
  82261. if (!this._physicsPlugin.isSupported()) {
  82262. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82263. + "Please make sure it is included.");
  82264. }
  82265. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82266. this.setGravity(gravity);
  82267. this.setTimeStep();
  82268. }
  82269. PhysicsEngine.prototype.setGravity = function (gravity) {
  82270. this.gravity = gravity;
  82271. this._physicsPlugin.setGravity(this.gravity);
  82272. };
  82273. /**
  82274. * Set the time step of the physics engine.
  82275. * default is 1/60.
  82276. * To slow it down, enter 1/600 for example.
  82277. * To speed it up, 1/30
  82278. * @param {number} newTimeStep the new timestep to apply to this world.
  82279. */
  82280. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82281. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82282. this._physicsPlugin.setTimeStep(newTimeStep);
  82283. };
  82284. /**
  82285. * Get the time step of the physics engine.
  82286. */
  82287. PhysicsEngine.prototype.getTimeStep = function () {
  82288. return this._physicsPlugin.getTimeStep();
  82289. };
  82290. PhysicsEngine.prototype.dispose = function () {
  82291. this._impostors.forEach(function (impostor) {
  82292. impostor.dispose();
  82293. });
  82294. this._physicsPlugin.dispose();
  82295. };
  82296. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82297. return this._physicsPlugin.name;
  82298. };
  82299. /**
  82300. * Adding a new impostor for the impostor tracking.
  82301. * This will be done by the impostor itself.
  82302. * @param {PhysicsImpostor} impostor the impostor to add
  82303. */
  82304. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82305. impostor.uniqueId = this._impostors.push(impostor);
  82306. //if no parent, generate the body
  82307. if (!impostor.parent) {
  82308. this._physicsPlugin.generatePhysicsBody(impostor);
  82309. }
  82310. };
  82311. /**
  82312. * Remove an impostor from the engine.
  82313. * This impostor and its mesh will not longer be updated by the physics engine.
  82314. * @param {PhysicsImpostor} impostor the impostor to remove
  82315. */
  82316. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82317. var index = this._impostors.indexOf(impostor);
  82318. if (index > -1) {
  82319. var removed = this._impostors.splice(index, 1);
  82320. //Is it needed?
  82321. if (removed.length) {
  82322. //this will also remove it from the world.
  82323. removed[0].physicsBody = null;
  82324. }
  82325. }
  82326. };
  82327. /**
  82328. * Add a joint to the physics engine
  82329. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82330. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82331. * @param {PhysicsJoint} the joint that will connect both impostors.
  82332. */
  82333. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82334. var impostorJoint = {
  82335. mainImpostor: mainImpostor,
  82336. connectedImpostor: connectedImpostor,
  82337. joint: joint
  82338. };
  82339. joint.physicsPlugin = this._physicsPlugin;
  82340. this._joints.push(impostorJoint);
  82341. this._physicsPlugin.generateJoint(impostorJoint);
  82342. };
  82343. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82344. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82345. return (impostorJoint.connectedImpostor === connectedImpostor
  82346. && impostorJoint.joint === joint
  82347. && impostorJoint.mainImpostor === mainImpostor);
  82348. });
  82349. if (matchingJoints.length) {
  82350. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82351. //TODO remove it from the list as well
  82352. }
  82353. };
  82354. /**
  82355. * Called by the scene. no need to call it.
  82356. */
  82357. PhysicsEngine.prototype._step = function (delta) {
  82358. var _this = this;
  82359. //check if any mesh has no body / requires an update
  82360. this._impostors.forEach(function (impostor) {
  82361. if (impostor.isBodyInitRequired()) {
  82362. _this._physicsPlugin.generatePhysicsBody(impostor);
  82363. }
  82364. });
  82365. if (delta > 0.1) {
  82366. delta = 0.1;
  82367. }
  82368. else if (delta <= 0) {
  82369. delta = 1.0 / 60.0;
  82370. }
  82371. this._physicsPlugin.executeStep(delta, this._impostors);
  82372. };
  82373. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82374. return this._physicsPlugin;
  82375. };
  82376. PhysicsEngine.prototype.getImpostors = function () {
  82377. return this._impostors;
  82378. };
  82379. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82380. for (var i = 0; i < this._impostors.length; ++i) {
  82381. if (this._impostors[i].object === object) {
  82382. return this._impostors[i];
  82383. }
  82384. }
  82385. return null;
  82386. };
  82387. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82388. for (var i = 0; i < this._impostors.length; ++i) {
  82389. if (this._impostors[i].physicsBody === body) {
  82390. return this._impostors[i];
  82391. }
  82392. }
  82393. return null;
  82394. };
  82395. // Statics
  82396. PhysicsEngine.Epsilon = 0.001;
  82397. return PhysicsEngine;
  82398. }());
  82399. BABYLON.PhysicsEngine = PhysicsEngine;
  82400. })(BABYLON || (BABYLON = {}));
  82401. //# sourceMappingURL=babylon.physicsEngine.js.map
  82402. var BABYLON;
  82403. (function (BABYLON) {
  82404. var PhysicsHelper = /** @class */ (function () {
  82405. function PhysicsHelper(scene) {
  82406. this._scene = scene;
  82407. this._physicsEngine = this._scene.getPhysicsEngine();
  82408. if (!this._physicsEngine) {
  82409. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82410. }
  82411. }
  82412. /**
  82413. * @param {Vector3} origin the origin of the explosion
  82414. * @param {number} radius the explosion radius
  82415. * @param {number} strength the explosion strength
  82416. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82417. */
  82418. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82419. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82420. if (!this._physicsEngine) {
  82421. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82422. return null;
  82423. }
  82424. var impostors = this._physicsEngine.getImpostors();
  82425. if (impostors.length === 0) {
  82426. return null;
  82427. }
  82428. var event = new PhysicsRadialExplosionEvent(this._scene);
  82429. impostors.forEach(function (impostor) {
  82430. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82431. if (!impostorForceAndContactPoint) {
  82432. return;
  82433. }
  82434. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82435. });
  82436. event.dispose(false);
  82437. return event;
  82438. };
  82439. /**
  82440. * @param {Vector3} origin the origin of the explosion
  82441. * @param {number} radius the explosion radius
  82442. * @param {number} strength the explosion strength
  82443. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82444. */
  82445. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82446. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82447. if (!this._physicsEngine) {
  82448. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82449. return null;
  82450. }
  82451. var impostors = this._physicsEngine.getImpostors();
  82452. if (impostors.length === 0) {
  82453. return null;
  82454. }
  82455. var event = new PhysicsRadialExplosionEvent(this._scene);
  82456. impostors.forEach(function (impostor) {
  82457. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82458. if (!impostorForceAndContactPoint) {
  82459. return;
  82460. }
  82461. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82462. });
  82463. event.dispose(false);
  82464. return event;
  82465. };
  82466. /**
  82467. * @param {Vector3} origin the origin of the explosion
  82468. * @param {number} radius the explosion radius
  82469. * @param {number} strength the explosion strength
  82470. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82471. */
  82472. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82473. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82474. if (!this._physicsEngine) {
  82475. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82476. return null;
  82477. }
  82478. var impostors = this._physicsEngine.getImpostors();
  82479. if (impostors.length === 0) {
  82480. return null;
  82481. }
  82482. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82483. event.dispose(false);
  82484. return event;
  82485. };
  82486. /**
  82487. * @param {Vector3} origin the origin of the updraft
  82488. * @param {number} radius the radius of the updraft
  82489. * @param {number} strength the strength of the updraft
  82490. * @param {number} height the height of the updraft
  82491. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82492. */
  82493. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82494. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82495. if (!this._physicsEngine) {
  82496. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82497. return null;
  82498. }
  82499. if (this._physicsEngine.getImpostors().length === 0) {
  82500. return null;
  82501. }
  82502. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82503. event.dispose(false);
  82504. return event;
  82505. };
  82506. /**
  82507. * @param {Vector3} origin the of the vortex
  82508. * @param {number} radius the radius of the vortex
  82509. * @param {number} strength the strength of the vortex
  82510. * @param {number} height the height of the vortex
  82511. */
  82512. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82513. if (!this._physicsEngine) {
  82514. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82515. return null;
  82516. }
  82517. if (this._physicsEngine.getImpostors().length === 0) {
  82518. return null;
  82519. }
  82520. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82521. event.dispose(false);
  82522. return event;
  82523. };
  82524. return PhysicsHelper;
  82525. }());
  82526. BABYLON.PhysicsHelper = PhysicsHelper;
  82527. /***** Radial explosion *****/
  82528. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82529. function PhysicsRadialExplosionEvent(scene) {
  82530. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82531. this._rays = [];
  82532. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82533. this._scene = scene;
  82534. }
  82535. /**
  82536. * Returns the data related to the radial explosion event (sphere & rays).
  82537. * @returns {PhysicsRadialExplosionEventData}
  82538. */
  82539. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82540. this._dataFetched = true;
  82541. return {
  82542. sphere: this._sphere,
  82543. rays: this._rays,
  82544. };
  82545. };
  82546. /**
  82547. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82548. * @param impostor
  82549. * @param {Vector3} origin the origin of the explosion
  82550. * @param {number} radius the explosion radius
  82551. * @param {number} strength the explosion strength
  82552. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82553. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82554. */
  82555. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82556. if (impostor.mass === 0) {
  82557. return null;
  82558. }
  82559. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82560. return null;
  82561. }
  82562. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82563. return null;
  82564. }
  82565. var impostorObjectCenter = impostor.getObjectCenter();
  82566. var direction = impostorObjectCenter.subtract(origin);
  82567. var ray = new BABYLON.Ray(origin, direction, radius);
  82568. this._rays.push(ray);
  82569. var hit = ray.intersectsMesh(impostor.object);
  82570. var contactPoint = hit.pickedPoint;
  82571. if (!contactPoint) {
  82572. return null;
  82573. }
  82574. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82575. if (distanceFromOrigin > radius) {
  82576. return null;
  82577. }
  82578. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82579. ? strength
  82580. : strength * (1 - (distanceFromOrigin / radius));
  82581. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82582. return { force: force, contactPoint: contactPoint };
  82583. };
  82584. /**
  82585. * Disposes the sphere.
  82586. * @param {bolean} force
  82587. */
  82588. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82589. var _this = this;
  82590. if (force === void 0) { force = true; }
  82591. if (force) {
  82592. this._sphere.dispose();
  82593. }
  82594. else {
  82595. setTimeout(function () {
  82596. if (!_this._dataFetched) {
  82597. _this._sphere.dispose();
  82598. }
  82599. }, 0);
  82600. }
  82601. };
  82602. /*** Helpers ***/
  82603. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82604. if (!this._sphere) {
  82605. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82606. this._sphere.isVisible = false;
  82607. }
  82608. };
  82609. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82610. var impostorObject = impostor.object;
  82611. this._prepareSphere();
  82612. this._sphere.position = origin;
  82613. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82614. this._sphere._updateBoundingInfo();
  82615. this._sphere.computeWorldMatrix(true);
  82616. return this._sphere.intersectsMesh(impostorObject, true);
  82617. };
  82618. return PhysicsRadialExplosionEvent;
  82619. }());
  82620. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82621. /***** Gravitational Field *****/
  82622. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82623. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82624. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82625. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82626. this._physicsHelper = physicsHelper;
  82627. this._scene = scene;
  82628. this._origin = origin;
  82629. this._radius = radius;
  82630. this._strength = strength;
  82631. this._falloff = falloff;
  82632. this._tickCallback = this._tick.bind(this);
  82633. }
  82634. /**
  82635. * Returns the data related to the gravitational field event (sphere).
  82636. * @returns {PhysicsGravitationalFieldEventData}
  82637. */
  82638. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82639. this._dataFetched = true;
  82640. return {
  82641. sphere: this._sphere,
  82642. };
  82643. };
  82644. /**
  82645. * Enables the gravitational field.
  82646. */
  82647. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82648. this._tickCallback.call(this);
  82649. this._scene.registerBeforeRender(this._tickCallback);
  82650. };
  82651. /**
  82652. * Disables the gravitational field.
  82653. */
  82654. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82655. this._scene.unregisterBeforeRender(this._tickCallback);
  82656. };
  82657. /**
  82658. * Disposes the sphere.
  82659. * @param {bolean} force
  82660. */
  82661. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82662. var _this = this;
  82663. if (force === void 0) { force = true; }
  82664. if (force) {
  82665. this._sphere.dispose();
  82666. }
  82667. else {
  82668. setTimeout(function () {
  82669. if (!_this._dataFetched) {
  82670. _this._sphere.dispose();
  82671. }
  82672. }, 0);
  82673. }
  82674. };
  82675. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82676. // Since the params won't change, we fetch the event only once
  82677. if (this._sphere) {
  82678. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82679. }
  82680. else {
  82681. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82682. if (radialExplosionEvent) {
  82683. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82684. }
  82685. }
  82686. };
  82687. return PhysicsGravitationalFieldEvent;
  82688. }());
  82689. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82690. /***** Updraft *****/
  82691. var PhysicsUpdraftEvent = /** @class */ (function () {
  82692. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82693. this._scene = _scene;
  82694. this._origin = _origin;
  82695. this._radius = _radius;
  82696. this._strength = _strength;
  82697. this._height = _height;
  82698. this._updraftMode = _updraftMode;
  82699. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82700. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82701. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82702. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82703. this._physicsEngine = this._scene.getPhysicsEngine();
  82704. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82705. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82706. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82707. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82708. }
  82709. this._tickCallback = this._tick.bind(this);
  82710. }
  82711. /**
  82712. * Returns the data related to the updraft event (cylinder).
  82713. * @returns {PhysicsUpdraftEventData}
  82714. */
  82715. PhysicsUpdraftEvent.prototype.getData = function () {
  82716. this._dataFetched = true;
  82717. return {
  82718. cylinder: this._cylinder,
  82719. };
  82720. };
  82721. /**
  82722. * Enables the updraft.
  82723. */
  82724. PhysicsUpdraftEvent.prototype.enable = function () {
  82725. this._tickCallback.call(this);
  82726. this._scene.registerBeforeRender(this._tickCallback);
  82727. };
  82728. /**
  82729. * Disables the cortex.
  82730. */
  82731. PhysicsUpdraftEvent.prototype.disable = function () {
  82732. this._scene.unregisterBeforeRender(this._tickCallback);
  82733. };
  82734. /**
  82735. * Disposes the sphere.
  82736. * @param {bolean} force
  82737. */
  82738. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82739. var _this = this;
  82740. if (force === void 0) { force = true; }
  82741. if (force) {
  82742. this._cylinder.dispose();
  82743. }
  82744. else {
  82745. setTimeout(function () {
  82746. if (!_this._dataFetched) {
  82747. _this._cylinder.dispose();
  82748. }
  82749. }, 0);
  82750. }
  82751. };
  82752. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82753. if (impostor.mass === 0) {
  82754. return null;
  82755. }
  82756. if (!this._intersectsWithCylinder(impostor)) {
  82757. return null;
  82758. }
  82759. var impostorObjectCenter = impostor.getObjectCenter();
  82760. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82761. var direction = this._originDirection;
  82762. }
  82763. else {
  82764. var direction = impostorObjectCenter.subtract(this._originTop);
  82765. }
  82766. var multiplier = this._strength * -1;
  82767. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82768. return { force: force, contactPoint: impostorObjectCenter };
  82769. };
  82770. PhysicsUpdraftEvent.prototype._tick = function () {
  82771. var _this = this;
  82772. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82773. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82774. if (!impostorForceAndContactPoint) {
  82775. return;
  82776. }
  82777. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82778. });
  82779. };
  82780. /*** Helpers ***/
  82781. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82782. if (!this._cylinder) {
  82783. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82784. height: this._height,
  82785. diameter: this._radius * 2,
  82786. }, this._scene);
  82787. this._cylinder.isVisible = false;
  82788. }
  82789. };
  82790. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82791. var impostorObject = impostor.object;
  82792. this._prepareCylinder();
  82793. this._cylinder.position = this._cylinderPosition;
  82794. return this._cylinder.intersectsMesh(impostorObject, true);
  82795. };
  82796. return PhysicsUpdraftEvent;
  82797. }());
  82798. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82799. /***** Vortex *****/
  82800. var PhysicsVortexEvent = /** @class */ (function () {
  82801. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82802. this._scene = _scene;
  82803. this._origin = _origin;
  82804. this._radius = _radius;
  82805. this._strength = _strength;
  82806. this._height = _height;
  82807. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82808. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82809. this._updraftMultiplier = 0.02;
  82810. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82811. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82812. this._physicsEngine = this._scene.getPhysicsEngine();
  82813. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82814. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82815. this._tickCallback = this._tick.bind(this);
  82816. }
  82817. /**
  82818. * Returns the data related to the vortex event (cylinder).
  82819. * @returns {PhysicsVortexEventData}
  82820. */
  82821. PhysicsVortexEvent.prototype.getData = function () {
  82822. this._dataFetched = true;
  82823. return {
  82824. cylinder: this._cylinder,
  82825. };
  82826. };
  82827. /**
  82828. * Enables the vortex.
  82829. */
  82830. PhysicsVortexEvent.prototype.enable = function () {
  82831. this._tickCallback.call(this);
  82832. this._scene.registerBeforeRender(this._tickCallback);
  82833. };
  82834. /**
  82835. * Disables the cortex.
  82836. */
  82837. PhysicsVortexEvent.prototype.disable = function () {
  82838. this._scene.unregisterBeforeRender(this._tickCallback);
  82839. };
  82840. /**
  82841. * Disposes the sphere.
  82842. * @param {bolean} force
  82843. */
  82844. PhysicsVortexEvent.prototype.dispose = function (force) {
  82845. var _this = this;
  82846. if (force === void 0) { force = true; }
  82847. if (force) {
  82848. this._cylinder.dispose();
  82849. }
  82850. else {
  82851. setTimeout(function () {
  82852. if (!_this._dataFetched) {
  82853. _this._cylinder.dispose();
  82854. }
  82855. }, 0);
  82856. }
  82857. };
  82858. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82859. if (impostor.mass === 0) {
  82860. return null;
  82861. }
  82862. if (!this._intersectsWithCylinder(impostor)) {
  82863. return null;
  82864. }
  82865. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82866. return null;
  82867. }
  82868. var impostorObjectCenter = impostor.getObjectCenter();
  82869. 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)
  82870. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82871. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82872. var hit = ray.intersectsMesh(impostor.object);
  82873. var contactPoint = hit.pickedPoint;
  82874. if (!contactPoint) {
  82875. return null;
  82876. }
  82877. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82878. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82879. var directionToOrigin = contactPoint.normalize();
  82880. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82881. directionToOrigin = directionToOrigin.negate();
  82882. }
  82883. // TODO: find a more physically based solution
  82884. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82885. var forceX = directionToOrigin.x * this._strength / 8;
  82886. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82887. var forceZ = directionToOrigin.z * this._strength / 8;
  82888. }
  82889. else {
  82890. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82891. var forceY = this._originTop.y * this._updraftMultiplier;
  82892. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82893. }
  82894. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82895. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82896. return { force: force, contactPoint: impostorObjectCenter };
  82897. };
  82898. PhysicsVortexEvent.prototype._tick = function () {
  82899. var _this = this;
  82900. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82901. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82902. if (!impostorForceAndContactPoint) {
  82903. return;
  82904. }
  82905. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82906. });
  82907. };
  82908. /*** Helpers ***/
  82909. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82910. if (!this._cylinder) {
  82911. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82912. height: this._height,
  82913. diameter: this._radius * 2,
  82914. }, this._scene);
  82915. this._cylinder.isVisible = false;
  82916. }
  82917. };
  82918. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82919. var impostorObject = impostor.object;
  82920. this._prepareCylinder();
  82921. this._cylinder.position = this._cylinderPosition;
  82922. return this._cylinder.intersectsMesh(impostorObject, true);
  82923. };
  82924. return PhysicsVortexEvent;
  82925. }());
  82926. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82927. /***** Enums *****/
  82928. /**
  82929. * The strenght of the force in correspondence to the distance of the affected object
  82930. */
  82931. var PhysicsRadialImpulseFalloff;
  82932. (function (PhysicsRadialImpulseFalloff) {
  82933. /** Defines that impulse is constant in strength across it's whole radius */
  82934. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82935. /** DEfines that impulse gets weaker if it's further from the origin */
  82936. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82937. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82938. /**
  82939. * The strenght of the force in correspondence to the distance of the affected object
  82940. */
  82941. var PhysicsUpdraftMode;
  82942. (function (PhysicsUpdraftMode) {
  82943. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82944. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82945. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82946. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82947. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82948. })(BABYLON || (BABYLON = {}));
  82949. //# sourceMappingURL=babylon.physicsHelper.js.map
  82950. var BABYLON;
  82951. (function (BABYLON) {
  82952. var CannonJSPlugin = /** @class */ (function () {
  82953. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82954. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82955. if (iterations === void 0) { iterations = 10; }
  82956. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82957. this.name = "CannonJSPlugin";
  82958. this._physicsMaterials = new Array();
  82959. this._fixedTimeStep = 1 / 60;
  82960. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82961. this.BJSCANNON = CANNON;
  82962. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82963. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82964. this._tmpPosition = BABYLON.Vector3.Zero();
  82965. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82966. this._tmpUnityRotation = new BABYLON.Quaternion();
  82967. if (!this.isSupported()) {
  82968. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82969. return;
  82970. }
  82971. this._extendNamespace();
  82972. this.world = new this.BJSCANNON.World();
  82973. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82974. this.world.solver.iterations = iterations;
  82975. }
  82976. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82977. this.world.gravity.copy(gravity);
  82978. };
  82979. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82980. this._fixedTimeStep = timeStep;
  82981. };
  82982. CannonJSPlugin.prototype.getTimeStep = function () {
  82983. return this._fixedTimeStep;
  82984. };
  82985. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82986. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82987. };
  82988. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82989. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82990. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82991. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82992. };
  82993. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82994. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82995. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82996. impostor.physicsBody.applyForce(impulse, worldPoint);
  82997. };
  82998. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82999. //parent-child relationship. Does this impostor has a parent impostor?
  83000. if (impostor.parent) {
  83001. if (impostor.physicsBody) {
  83002. this.removePhysicsBody(impostor);
  83003. //TODO is that needed?
  83004. impostor.forceUpdate();
  83005. }
  83006. return;
  83007. }
  83008. //should a new body be created for this impostor?
  83009. if (impostor.isBodyInitRequired()) {
  83010. var shape = this._createShape(impostor);
  83011. //unregister events, if body is being changed
  83012. var oldBody = impostor.physicsBody;
  83013. if (oldBody) {
  83014. this.removePhysicsBody(impostor);
  83015. }
  83016. //create the body and material
  83017. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83018. var bodyCreationObject = {
  83019. mass: impostor.getParam("mass"),
  83020. material: material
  83021. };
  83022. // A simple extend, in case native options were used.
  83023. var nativeOptions = impostor.getParam("nativeOptions");
  83024. for (var key in nativeOptions) {
  83025. if (nativeOptions.hasOwnProperty(key)) {
  83026. bodyCreationObject[key] = nativeOptions[key];
  83027. }
  83028. }
  83029. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83030. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83031. this.world.addEventListener("preStep", impostor.beforeStep);
  83032. this.world.addEventListener("postStep", impostor.afterStep);
  83033. impostor.physicsBody.addShape(shape);
  83034. this.world.add(impostor.physicsBody);
  83035. //try to keep the body moving in the right direction by taking old properties.
  83036. //Should be tested!
  83037. if (oldBody) {
  83038. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83039. impostor.physicsBody[param].copy(oldBody[param]);
  83040. });
  83041. }
  83042. this._processChildMeshes(impostor);
  83043. }
  83044. //now update the body's transformation
  83045. this._updatePhysicsBodyTransformation(impostor);
  83046. };
  83047. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83048. var _this = this;
  83049. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83050. var currentRotation = mainImpostor.object.rotationQuaternion;
  83051. if (meshChildren.length) {
  83052. var processMesh = function (localPosition, mesh) {
  83053. if (!currentRotation || !mesh.rotationQuaternion) {
  83054. return;
  83055. }
  83056. var childImpostor = mesh.getPhysicsImpostor();
  83057. if (childImpostor) {
  83058. var parent = childImpostor.parent;
  83059. if (parent !== mainImpostor) {
  83060. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83061. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83062. if (childImpostor.physicsBody) {
  83063. _this.removePhysicsBody(childImpostor);
  83064. childImpostor.physicsBody = null;
  83065. }
  83066. childImpostor.parent = mainImpostor;
  83067. childImpostor.resetUpdateFlags();
  83068. 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));
  83069. //Add the mass of the children.
  83070. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83071. }
  83072. }
  83073. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83074. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83075. };
  83076. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83077. }
  83078. };
  83079. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83080. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83081. this.world.removeEventListener("preStep", impostor.beforeStep);
  83082. this.world.removeEventListener("postStep", impostor.afterStep);
  83083. this.world.remove(impostor.physicsBody);
  83084. };
  83085. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83086. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83087. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83088. if (!mainBody || !connectedBody) {
  83089. return;
  83090. }
  83091. var constraint;
  83092. var jointData = impostorJoint.joint.jointData;
  83093. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83094. var constraintData = {
  83095. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83096. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83097. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83098. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83099. maxForce: jointData.nativeParams.maxForce,
  83100. collideConnected: !!jointData.collision
  83101. };
  83102. switch (impostorJoint.joint.type) {
  83103. case BABYLON.PhysicsJoint.HingeJoint:
  83104. case BABYLON.PhysicsJoint.Hinge2Joint:
  83105. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83106. break;
  83107. case BABYLON.PhysicsJoint.DistanceJoint:
  83108. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83109. break;
  83110. case BABYLON.PhysicsJoint.SpringJoint:
  83111. var springData = jointData;
  83112. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83113. restLength: springData.length,
  83114. stiffness: springData.stiffness,
  83115. damping: springData.damping,
  83116. localAnchorA: constraintData.pivotA,
  83117. localAnchorB: constraintData.pivotB
  83118. });
  83119. break;
  83120. case BABYLON.PhysicsJoint.LockJoint:
  83121. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83122. break;
  83123. case BABYLON.PhysicsJoint.PointToPointJoint:
  83124. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83125. default:
  83126. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83127. break;
  83128. }
  83129. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83130. constraint.collideConnected = !!jointData.collision;
  83131. impostorJoint.joint.physicsJoint = constraint;
  83132. //don't add spring as constraint, as it is not one.
  83133. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83134. this.world.addConstraint(constraint);
  83135. }
  83136. else {
  83137. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83138. constraint.applyForce();
  83139. });
  83140. }
  83141. };
  83142. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83143. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83144. };
  83145. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83146. var index;
  83147. var mat;
  83148. for (index = 0; index < this._physicsMaterials.length; index++) {
  83149. mat = this._physicsMaterials[index];
  83150. if (mat.friction === friction && mat.restitution === restitution) {
  83151. return mat;
  83152. }
  83153. }
  83154. var currentMat = new this.BJSCANNON.Material(name);
  83155. currentMat.friction = friction;
  83156. currentMat.restitution = restitution;
  83157. this._physicsMaterials.push(currentMat);
  83158. return currentMat;
  83159. };
  83160. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83161. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83162. };
  83163. CannonJSPlugin.prototype._createShape = function (impostor) {
  83164. var object = impostor.object;
  83165. var returnValue;
  83166. var extendSize = impostor.getObjectExtendSize();
  83167. switch (impostor.type) {
  83168. case BABYLON.PhysicsImpostor.SphereImpostor:
  83169. var radiusX = extendSize.x;
  83170. var radiusY = extendSize.y;
  83171. var radiusZ = extendSize.z;
  83172. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83173. break;
  83174. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83175. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83176. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83177. break;
  83178. case BABYLON.PhysicsImpostor.BoxImpostor:
  83179. var box = extendSize.scale(0.5);
  83180. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83181. break;
  83182. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83183. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83184. returnValue = new this.BJSCANNON.Plane();
  83185. break;
  83186. case BABYLON.PhysicsImpostor.MeshImpostor:
  83187. // should transform the vertex data to world coordinates!!
  83188. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83189. var rawFaces = object.getIndices ? object.getIndices() : [];
  83190. if (!rawVerts)
  83191. return;
  83192. // get only scale! so the object could transform correctly.
  83193. var oldPosition = object.position.clone();
  83194. var oldRotation = object.rotation && object.rotation.clone();
  83195. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83196. object.position.copyFromFloats(0, 0, 0);
  83197. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83198. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83199. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83200. var transform = object.computeWorldMatrix(true);
  83201. // convert rawVerts to object space
  83202. var temp = new Array();
  83203. var index;
  83204. for (index = 0; index < rawVerts.length; index += 3) {
  83205. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83206. }
  83207. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83208. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83209. //now set back the transformation!
  83210. object.position.copyFrom(oldPosition);
  83211. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83212. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83213. break;
  83214. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83215. var oldPosition2 = object.position.clone();
  83216. var oldRotation2 = object.rotation && object.rotation.clone();
  83217. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83218. object.position.copyFromFloats(0, 0, 0);
  83219. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83220. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83221. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83222. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83223. returnValue = this._createHeightmap(object);
  83224. object.position.copyFrom(oldPosition2);
  83225. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83226. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83227. object.computeWorldMatrix(true);
  83228. break;
  83229. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83230. returnValue = new this.BJSCANNON.Particle();
  83231. break;
  83232. }
  83233. return returnValue;
  83234. };
  83235. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83236. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83237. var transform = object.computeWorldMatrix(true);
  83238. // convert rawVerts to object space
  83239. var temp = new Array();
  83240. var index;
  83241. for (index = 0; index < pos.length; index += 3) {
  83242. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83243. }
  83244. pos = temp;
  83245. var matrix = new Array();
  83246. //For now pointDepth will not be used and will be automatically calculated.
  83247. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83248. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83249. var boundingInfo = object.getBoundingInfo();
  83250. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83251. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83252. var elementSize = dim * 2 / arraySize;
  83253. for (var i = 0; i < pos.length; i = i + 3) {
  83254. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83255. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83256. var y = -pos[i + 2] + minY;
  83257. if (!matrix[x]) {
  83258. matrix[x] = [];
  83259. }
  83260. if (!matrix[x][z]) {
  83261. matrix[x][z] = y;
  83262. }
  83263. matrix[x][z] = Math.max(y, matrix[x][z]);
  83264. }
  83265. for (var x = 0; x <= arraySize; ++x) {
  83266. if (!matrix[x]) {
  83267. var loc = 1;
  83268. while (!matrix[(x + loc) % arraySize]) {
  83269. loc++;
  83270. }
  83271. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83272. //console.log("missing x", x);
  83273. }
  83274. for (var z = 0; z <= arraySize; ++z) {
  83275. if (!matrix[x][z]) {
  83276. var loc = 1;
  83277. var newValue;
  83278. while (newValue === undefined) {
  83279. newValue = matrix[x][(z + loc++) % arraySize];
  83280. }
  83281. matrix[x][z] = newValue;
  83282. }
  83283. }
  83284. }
  83285. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83286. elementSize: elementSize
  83287. });
  83288. //For future reference, needed for body transformation
  83289. shape.minY = minY;
  83290. return shape;
  83291. };
  83292. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83293. var object = impostor.object;
  83294. //make sure it is updated...
  83295. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83296. // The delta between the mesh position and the mesh bounding box center
  83297. var bInfo = object.getBoundingInfo();
  83298. if (!bInfo)
  83299. return;
  83300. var center = impostor.getObjectCenter();
  83301. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83302. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83303. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83304. this._tmpPosition.copyFrom(center);
  83305. var quaternion = object.rotationQuaternion;
  83306. if (!quaternion) {
  83307. return;
  83308. }
  83309. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83310. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83311. //-90 DEG in X, precalculated
  83312. quaternion = quaternion.multiply(this._minus90X);
  83313. //Invert! (Precalculated, 90 deg in X)
  83314. //No need to clone. this will never change.
  83315. impostor.setDeltaRotation(this._plus90X);
  83316. }
  83317. //If it is a heightfield, if should be centered.
  83318. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83319. var mesh = object;
  83320. var boundingInfo = mesh.getBoundingInfo();
  83321. //calculate the correct body position:
  83322. var rotationQuaternion = mesh.rotationQuaternion;
  83323. mesh.rotationQuaternion = this._tmpUnityRotation;
  83324. mesh.computeWorldMatrix(true);
  83325. //get original center with no rotation
  83326. var c = center.clone();
  83327. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83328. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83329. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83330. mesh.setPreTransformMatrix(p);
  83331. mesh.computeWorldMatrix(true);
  83332. //calculate the translation
  83333. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83334. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83335. //add it inverted to the delta
  83336. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83337. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83338. //rotation is back
  83339. mesh.rotationQuaternion = rotationQuaternion;
  83340. mesh.setPreTransformMatrix(oldPivot);
  83341. mesh.computeWorldMatrix(true);
  83342. }
  83343. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83344. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83345. //this._tmpPosition.copyFrom(object.position);
  83346. }
  83347. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83348. //Now update the impostor object
  83349. impostor.physicsBody.position.copy(this._tmpPosition);
  83350. impostor.physicsBody.quaternion.copy(quaternion);
  83351. };
  83352. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83353. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83354. if (impostor.object.rotationQuaternion) {
  83355. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83356. }
  83357. };
  83358. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83359. impostor.physicsBody.position.copy(newPosition);
  83360. impostor.physicsBody.quaternion.copy(newRotation);
  83361. };
  83362. CannonJSPlugin.prototype.isSupported = function () {
  83363. return this.BJSCANNON !== undefined;
  83364. };
  83365. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83366. impostor.physicsBody.velocity.copy(velocity);
  83367. };
  83368. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83369. impostor.physicsBody.angularVelocity.copy(velocity);
  83370. };
  83371. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83372. var v = impostor.physicsBody.velocity;
  83373. if (!v) {
  83374. return null;
  83375. }
  83376. return new BABYLON.Vector3(v.x, v.y, v.z);
  83377. };
  83378. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83379. var v = impostor.physicsBody.angularVelocity;
  83380. if (!v) {
  83381. return null;
  83382. }
  83383. return new BABYLON.Vector3(v.x, v.y, v.z);
  83384. };
  83385. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83386. impostor.physicsBody.mass = mass;
  83387. impostor.physicsBody.updateMassProperties();
  83388. };
  83389. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83390. return impostor.physicsBody.mass;
  83391. };
  83392. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83393. return impostor.physicsBody.material.friction;
  83394. };
  83395. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83396. impostor.physicsBody.material.friction = friction;
  83397. };
  83398. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83399. return impostor.physicsBody.material.restitution;
  83400. };
  83401. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83402. impostor.physicsBody.material.restitution = restitution;
  83403. };
  83404. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83405. impostor.physicsBody.sleep();
  83406. };
  83407. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83408. impostor.physicsBody.wakeUp();
  83409. };
  83410. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83411. joint.physicsJoint.distance = maxDistance;
  83412. };
  83413. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83414. // if (!motorIndex) {
  83415. // joint.physicsJoint.enableMotor();
  83416. // }
  83417. // }
  83418. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83419. // if (!motorIndex) {
  83420. // joint.physicsJoint.disableMotor();
  83421. // }
  83422. // }
  83423. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83424. if (!motorIndex) {
  83425. joint.physicsJoint.enableMotor();
  83426. joint.physicsJoint.setMotorSpeed(speed);
  83427. if (maxForce) {
  83428. this.setLimit(joint, maxForce);
  83429. }
  83430. }
  83431. };
  83432. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83433. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83434. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83435. };
  83436. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83437. var body = impostor.physicsBody;
  83438. mesh.position.x = body.position.x;
  83439. mesh.position.y = body.position.y;
  83440. mesh.position.z = body.position.z;
  83441. if (mesh.rotationQuaternion) {
  83442. mesh.rotationQuaternion.x = body.quaternion.x;
  83443. mesh.rotationQuaternion.y = body.quaternion.y;
  83444. mesh.rotationQuaternion.z = body.quaternion.z;
  83445. mesh.rotationQuaternion.w = body.quaternion.w;
  83446. }
  83447. };
  83448. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83449. var shape = impostor.physicsBody.shapes[0];
  83450. return shape.boundingSphereRadius;
  83451. };
  83452. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83453. var shape = impostor.physicsBody.shapes[0];
  83454. result.x = shape.halfExtents.x * 2;
  83455. result.y = shape.halfExtents.y * 2;
  83456. result.z = shape.halfExtents.z * 2;
  83457. };
  83458. CannonJSPlugin.prototype.dispose = function () {
  83459. };
  83460. CannonJSPlugin.prototype._extendNamespace = function () {
  83461. //this will force cannon to execute at least one step when using interpolation
  83462. var step_tmp1 = new this.BJSCANNON.Vec3();
  83463. var Engine = this.BJSCANNON;
  83464. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83465. maxSubSteps = maxSubSteps || 10;
  83466. timeSinceLastCalled = timeSinceLastCalled || 0;
  83467. if (timeSinceLastCalled === 0) {
  83468. this.internalStep(dt);
  83469. this.time += dt;
  83470. }
  83471. else {
  83472. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83473. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83474. var t0 = performance.now();
  83475. for (var i = 0; i !== internalSteps; i++) {
  83476. this.internalStep(dt);
  83477. if (performance.now() - t0 > dt * 1000) {
  83478. break;
  83479. }
  83480. }
  83481. this.time += timeSinceLastCalled;
  83482. var h = this.time % dt;
  83483. var h_div_dt = h / dt;
  83484. var interpvelo = step_tmp1;
  83485. var bodies = this.bodies;
  83486. for (var j = 0; j !== bodies.length; j++) {
  83487. var b = bodies[j];
  83488. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83489. b.position.vsub(b.previousPosition, interpvelo);
  83490. interpvelo.scale(h_div_dt, interpvelo);
  83491. b.position.vadd(interpvelo, b.interpolatedPosition);
  83492. }
  83493. else {
  83494. b.interpolatedPosition.copy(b.position);
  83495. b.interpolatedQuaternion.copy(b.quaternion);
  83496. }
  83497. }
  83498. }
  83499. };
  83500. };
  83501. return CannonJSPlugin;
  83502. }());
  83503. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83504. })(BABYLON || (BABYLON = {}));
  83505. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83506. var BABYLON;
  83507. (function (BABYLON) {
  83508. var OimoJSPlugin = /** @class */ (function () {
  83509. function OimoJSPlugin(iterations) {
  83510. this.name = "OimoJSPlugin";
  83511. this._tmpImpostorsArray = [];
  83512. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83513. this.BJSOIMO = OIMO;
  83514. this.world = new this.BJSOIMO.World({
  83515. iterations: iterations
  83516. });
  83517. this.world.clear();
  83518. }
  83519. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83520. this.world.gravity.copy(gravity);
  83521. };
  83522. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83523. this.world.timeStep = timeStep;
  83524. };
  83525. OimoJSPlugin.prototype.getTimeStep = function () {
  83526. return this.world.timeStep;
  83527. };
  83528. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83529. var _this = this;
  83530. impostors.forEach(function (impostor) {
  83531. impostor.beforeStep();
  83532. });
  83533. this.world.step();
  83534. impostors.forEach(function (impostor) {
  83535. impostor.afterStep();
  83536. //update the ordered impostors array
  83537. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83538. });
  83539. //check for collisions
  83540. var contact = this.world.contacts;
  83541. while (contact !== null) {
  83542. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83543. contact = contact.next;
  83544. continue;
  83545. }
  83546. //is this body colliding with any other? get the impostor
  83547. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83548. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83549. if (!mainImpostor || !collidingImpostor) {
  83550. contact = contact.next;
  83551. continue;
  83552. }
  83553. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83554. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83555. contact = contact.next;
  83556. }
  83557. };
  83558. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83559. var mass = impostor.physicsBody.mass;
  83560. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83561. };
  83562. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83563. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83564. this.applyImpulse(impostor, force, contactPoint);
  83565. };
  83566. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83567. var _this = this;
  83568. //parent-child relationship. Does this impostor has a parent impostor?
  83569. if (impostor.parent) {
  83570. if (impostor.physicsBody) {
  83571. this.removePhysicsBody(impostor);
  83572. //TODO is that needed?
  83573. impostor.forceUpdate();
  83574. }
  83575. return;
  83576. }
  83577. if (impostor.isBodyInitRequired()) {
  83578. var bodyConfig = {
  83579. name: impostor.uniqueId,
  83580. //Oimo must have mass, also for static objects.
  83581. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83582. size: [],
  83583. type: [],
  83584. pos: [],
  83585. posShape: [],
  83586. rot: [],
  83587. rotShape: [],
  83588. move: impostor.getParam("mass") !== 0,
  83589. density: impostor.getParam("mass"),
  83590. friction: impostor.getParam("friction"),
  83591. restitution: impostor.getParam("restitution"),
  83592. //Supporting older versions of Oimo
  83593. world: this.world
  83594. };
  83595. var impostors = [impostor];
  83596. var addToArray = function (parent) {
  83597. if (!parent.getChildMeshes)
  83598. return;
  83599. parent.getChildMeshes().forEach(function (m) {
  83600. if (m.physicsImpostor) {
  83601. impostors.push(m.physicsImpostor);
  83602. //m.physicsImpostor._init();
  83603. }
  83604. });
  83605. };
  83606. addToArray(impostor.object);
  83607. var checkWithEpsilon_1 = function (value) {
  83608. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83609. };
  83610. impostors.forEach(function (i) {
  83611. if (!i.object.rotationQuaternion) {
  83612. return;
  83613. }
  83614. //get the correct bounding box
  83615. var oldQuaternion = i.object.rotationQuaternion;
  83616. var rot = oldQuaternion.toEulerAngles();
  83617. var extendSize = i.getObjectExtendSize();
  83618. var radToDeg = 57.295779513082320876;
  83619. if (i === impostor) {
  83620. var center = impostor.getObjectCenter();
  83621. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83622. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83623. //Can also use Array.prototype.push.apply
  83624. bodyConfig.pos.push(center.x);
  83625. bodyConfig.pos.push(center.y);
  83626. bodyConfig.pos.push(center.z);
  83627. bodyConfig.posShape.push(0, 0, 0);
  83628. //tmp solution
  83629. bodyConfig.rot.push(rot.x * radToDeg);
  83630. bodyConfig.rot.push(rot.y * radToDeg);
  83631. bodyConfig.rot.push(rot.z * radToDeg);
  83632. bodyConfig.rotShape.push(0, 0, 0);
  83633. }
  83634. else {
  83635. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83636. bodyConfig.posShape.push(localPosition.x);
  83637. bodyConfig.posShape.push(localPosition.y);
  83638. bodyConfig.posShape.push(localPosition.z);
  83639. bodyConfig.pos.push(0, 0, 0);
  83640. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83641. bodyConfig.rot.push(0);
  83642. bodyConfig.rot.push(0);
  83643. bodyConfig.rot.push(0);
  83644. bodyConfig.rotShape.push(rot.x * radToDeg);
  83645. bodyConfig.rotShape.push(rot.y * radToDeg);
  83646. bodyConfig.rotShape.push(rot.z * radToDeg);
  83647. }
  83648. // register mesh
  83649. switch (i.type) {
  83650. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83651. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83652. case BABYLON.PhysicsImpostor.SphereImpostor:
  83653. var radiusX = extendSize.x;
  83654. var radiusY = extendSize.y;
  83655. var radiusZ = extendSize.z;
  83656. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83657. bodyConfig.type.push('sphere');
  83658. //due to the way oimo works with compounds, add 3 times
  83659. bodyConfig.size.push(size);
  83660. bodyConfig.size.push(size);
  83661. bodyConfig.size.push(size);
  83662. break;
  83663. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83664. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83665. var sizeY = checkWithEpsilon_1(extendSize.y);
  83666. bodyConfig.type.push('cylinder');
  83667. bodyConfig.size.push(sizeX);
  83668. bodyConfig.size.push(sizeY);
  83669. //due to the way oimo works with compounds, add one more value.
  83670. bodyConfig.size.push(sizeY);
  83671. break;
  83672. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83673. case BABYLON.PhysicsImpostor.BoxImpostor:
  83674. default:
  83675. var sizeX = checkWithEpsilon_1(extendSize.x);
  83676. var sizeY = checkWithEpsilon_1(extendSize.y);
  83677. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83678. bodyConfig.type.push('box');
  83679. //if (i === impostor) {
  83680. bodyConfig.size.push(sizeX);
  83681. bodyConfig.size.push(sizeY);
  83682. bodyConfig.size.push(sizeZ);
  83683. //} else {
  83684. // bodyConfig.size.push(0,0,0);
  83685. //}
  83686. break;
  83687. }
  83688. //actually not needed, but hey...
  83689. i.object.rotationQuaternion = oldQuaternion;
  83690. });
  83691. impostor.physicsBody = this.world.add(bodyConfig);
  83692. }
  83693. else {
  83694. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83695. }
  83696. impostor.setDeltaPosition(this._tmpPositionVector);
  83697. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83698. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83699. };
  83700. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83701. //impostor.physicsBody.dispose();
  83702. //Same as : (older oimo versions)
  83703. this.world.removeRigidBody(impostor.physicsBody);
  83704. };
  83705. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83706. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83707. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83708. if (!mainBody || !connectedBody) {
  83709. return;
  83710. }
  83711. var jointData = impostorJoint.joint.jointData;
  83712. var options = jointData.nativeParams || {};
  83713. var type;
  83714. var nativeJointData = {
  83715. body1: mainBody,
  83716. body2: connectedBody,
  83717. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83718. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83719. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83720. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83721. min: options.min,
  83722. max: options.max,
  83723. collision: options.collision || jointData.collision,
  83724. spring: options.spring,
  83725. //supporting older version of Oimo
  83726. world: this.world
  83727. };
  83728. switch (impostorJoint.joint.type) {
  83729. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83730. type = "jointBall";
  83731. break;
  83732. case BABYLON.PhysicsJoint.SpringJoint:
  83733. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83734. var springData = jointData;
  83735. nativeJointData.min = springData.length || nativeJointData.min;
  83736. //Max should also be set, just make sure it is at least min
  83737. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83738. case BABYLON.PhysicsJoint.DistanceJoint:
  83739. type = "jointDistance";
  83740. nativeJointData.max = jointData.maxDistance;
  83741. break;
  83742. case BABYLON.PhysicsJoint.PrismaticJoint:
  83743. type = "jointPrisme";
  83744. break;
  83745. case BABYLON.PhysicsJoint.SliderJoint:
  83746. type = "jointSlide";
  83747. break;
  83748. case BABYLON.PhysicsJoint.WheelJoint:
  83749. type = "jointWheel";
  83750. break;
  83751. case BABYLON.PhysicsJoint.HingeJoint:
  83752. default:
  83753. type = "jointHinge";
  83754. break;
  83755. }
  83756. nativeJointData.type = type;
  83757. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83758. };
  83759. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83760. //Bug in Oimo prevents us from disposing a joint in the playground
  83761. //joint.joint.physicsJoint.dispose();
  83762. //So we will bruteforce it!
  83763. try {
  83764. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83765. }
  83766. catch (e) {
  83767. BABYLON.Tools.Warn(e);
  83768. }
  83769. };
  83770. OimoJSPlugin.prototype.isSupported = function () {
  83771. return this.BJSOIMO !== undefined;
  83772. };
  83773. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83774. if (!impostor.physicsBody.sleeping) {
  83775. //TODO check that
  83776. /*if (impostor.physicsBody.shapes.next) {
  83777. var parentShape = this._getLastShape(impostor.physicsBody);
  83778. impostor.object.position.copyFrom(parentShape.position);
  83779. console.log(parentShape.position);
  83780. } else {*/
  83781. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83782. //}
  83783. if (impostor.object.rotationQuaternion) {
  83784. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83785. }
  83786. }
  83787. };
  83788. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83789. var body = impostor.physicsBody;
  83790. body.position.copy(newPosition);
  83791. body.orientation.copy(newRotation);
  83792. body.syncShapes();
  83793. body.awake();
  83794. };
  83795. /*private _getLastShape(body: any): any {
  83796. var lastShape = body.shapes;
  83797. while (lastShape.next) {
  83798. lastShape = lastShape.next;
  83799. }
  83800. return lastShape;
  83801. }*/
  83802. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83803. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83804. };
  83805. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83806. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83807. };
  83808. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83809. var v = impostor.physicsBody.linearVelocity;
  83810. if (!v) {
  83811. return null;
  83812. }
  83813. return new BABYLON.Vector3(v.x, v.y, v.z);
  83814. };
  83815. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83816. var v = impostor.physicsBody.angularVelocity;
  83817. if (!v) {
  83818. return null;
  83819. }
  83820. return new BABYLON.Vector3(v.x, v.y, v.z);
  83821. };
  83822. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83823. var staticBody = mass === 0;
  83824. //this will actually set the body's density and not its mass.
  83825. //But this is how oimo treats the mass variable.
  83826. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83827. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83828. };
  83829. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83830. return impostor.physicsBody.shapes.density;
  83831. };
  83832. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83833. return impostor.physicsBody.shapes.friction;
  83834. };
  83835. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83836. impostor.physicsBody.shapes.friction = friction;
  83837. };
  83838. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83839. return impostor.physicsBody.shapes.restitution;
  83840. };
  83841. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83842. impostor.physicsBody.shapes.restitution = restitution;
  83843. };
  83844. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83845. impostor.physicsBody.sleep();
  83846. };
  83847. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83848. impostor.physicsBody.awake();
  83849. };
  83850. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83851. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83852. if (minDistance !== void 0) {
  83853. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83854. }
  83855. };
  83856. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83857. //TODO separate rotational and transational motors.
  83858. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83859. if (motor) {
  83860. motor.setMotor(speed, maxForce);
  83861. }
  83862. };
  83863. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83864. //TODO separate rotational and transational motors.
  83865. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83866. if (motor) {
  83867. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83868. }
  83869. };
  83870. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83871. var body = impostor.physicsBody;
  83872. mesh.position.x = body.position.x;
  83873. mesh.position.y = body.position.y;
  83874. mesh.position.z = body.position.z;
  83875. if (mesh.rotationQuaternion) {
  83876. mesh.rotationQuaternion.x = body.orientation.x;
  83877. mesh.rotationQuaternion.y = body.orientation.y;
  83878. mesh.rotationQuaternion.z = body.orientation.z;
  83879. mesh.rotationQuaternion.w = body.orientation.s;
  83880. }
  83881. };
  83882. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83883. return impostor.physicsBody.shapes.radius;
  83884. };
  83885. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83886. var shape = impostor.physicsBody.shapes;
  83887. result.x = shape.halfWidth * 2;
  83888. result.y = shape.halfHeight * 2;
  83889. result.z = shape.halfDepth * 2;
  83890. };
  83891. OimoJSPlugin.prototype.dispose = function () {
  83892. this.world.clear();
  83893. };
  83894. return OimoJSPlugin;
  83895. }());
  83896. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83897. })(BABYLON || (BABYLON = {}));
  83898. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83899. var BABYLON;
  83900. (function (BABYLON) {
  83901. /*
  83902. * Based on jsTGALoader - Javascript loader for TGA file
  83903. * By Vincent Thibault
  83904. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83905. */
  83906. var TGATools = /** @class */ (function () {
  83907. function TGATools() {
  83908. }
  83909. TGATools.GetTGAHeader = function (data) {
  83910. var offset = 0;
  83911. var header = {
  83912. id_length: data[offset++],
  83913. colormap_type: data[offset++],
  83914. image_type: data[offset++],
  83915. colormap_index: data[offset++] | data[offset++] << 8,
  83916. colormap_length: data[offset++] | data[offset++] << 8,
  83917. colormap_size: data[offset++],
  83918. origin: [
  83919. data[offset++] | data[offset++] << 8,
  83920. data[offset++] | data[offset++] << 8
  83921. ],
  83922. width: data[offset++] | data[offset++] << 8,
  83923. height: data[offset++] | data[offset++] << 8,
  83924. pixel_size: data[offset++],
  83925. flags: data[offset++]
  83926. };
  83927. return header;
  83928. };
  83929. TGATools.UploadContent = function (gl, data) {
  83930. // Not enough data to contain header ?
  83931. if (data.length < 19) {
  83932. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83933. return;
  83934. }
  83935. // Read Header
  83936. var offset = 18;
  83937. var header = TGATools.GetTGAHeader(data);
  83938. // Assume it's a valid Targa file.
  83939. if (header.id_length + offset > data.length) {
  83940. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83941. return;
  83942. }
  83943. // Skip not needed data
  83944. offset += header.id_length;
  83945. var use_rle = false;
  83946. var use_pal = false;
  83947. var use_grey = false;
  83948. // Get some informations.
  83949. switch (header.image_type) {
  83950. case TGATools._TYPE_RLE_INDEXED:
  83951. use_rle = true;
  83952. case TGATools._TYPE_INDEXED:
  83953. use_pal = true;
  83954. break;
  83955. case TGATools._TYPE_RLE_RGB:
  83956. use_rle = true;
  83957. case TGATools._TYPE_RGB:
  83958. // use_rgb = true;
  83959. break;
  83960. case TGATools._TYPE_RLE_GREY:
  83961. use_rle = true;
  83962. case TGATools._TYPE_GREY:
  83963. use_grey = true;
  83964. break;
  83965. }
  83966. var pixel_data;
  83967. // var numAlphaBits = header.flags & 0xf;
  83968. var pixel_size = header.pixel_size >> 3;
  83969. var pixel_total = header.width * header.height * pixel_size;
  83970. // Read palettes
  83971. var palettes;
  83972. if (use_pal) {
  83973. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83974. }
  83975. // Read LRE
  83976. if (use_rle) {
  83977. pixel_data = new Uint8Array(pixel_total);
  83978. var c, count, i;
  83979. var localOffset = 0;
  83980. var pixels = new Uint8Array(pixel_size);
  83981. while (offset < pixel_total && localOffset < pixel_total) {
  83982. c = data[offset++];
  83983. count = (c & 0x7f) + 1;
  83984. // RLE pixels
  83985. if (c & 0x80) {
  83986. // Bind pixel tmp array
  83987. for (i = 0; i < pixel_size; ++i) {
  83988. pixels[i] = data[offset++];
  83989. }
  83990. // Copy pixel array
  83991. for (i = 0; i < count; ++i) {
  83992. pixel_data.set(pixels, localOffset + i * pixel_size);
  83993. }
  83994. localOffset += pixel_size * count;
  83995. }
  83996. // Raw pixels
  83997. else {
  83998. count *= pixel_size;
  83999. for (i = 0; i < count; ++i) {
  84000. pixel_data[localOffset + i] = data[offset++];
  84001. }
  84002. localOffset += count;
  84003. }
  84004. }
  84005. }
  84006. // RAW Pixels
  84007. else {
  84008. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84009. }
  84010. // Load to texture
  84011. var x_start, y_start, x_step, y_step, y_end, x_end;
  84012. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84013. default:
  84014. case TGATools._ORIGIN_UL:
  84015. x_start = 0;
  84016. x_step = 1;
  84017. x_end = header.width;
  84018. y_start = 0;
  84019. y_step = 1;
  84020. y_end = header.height;
  84021. break;
  84022. case TGATools._ORIGIN_BL:
  84023. x_start = 0;
  84024. x_step = 1;
  84025. x_end = header.width;
  84026. y_start = header.height - 1;
  84027. y_step = -1;
  84028. y_end = -1;
  84029. break;
  84030. case TGATools._ORIGIN_UR:
  84031. x_start = header.width - 1;
  84032. x_step = -1;
  84033. x_end = -1;
  84034. y_start = 0;
  84035. y_step = 1;
  84036. y_end = header.height;
  84037. break;
  84038. case TGATools._ORIGIN_BR:
  84039. x_start = header.width - 1;
  84040. x_step = -1;
  84041. x_end = -1;
  84042. y_start = header.height - 1;
  84043. y_step = -1;
  84044. y_end = -1;
  84045. break;
  84046. }
  84047. // Load the specify method
  84048. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84049. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84050. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84051. };
  84052. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84053. var image = pixel_data, colormap = palettes;
  84054. var width = header.width, height = header.height;
  84055. var color, i = 0, x, y;
  84056. var imageData = new Uint8Array(width * height * 4);
  84057. for (y = y_start; y !== y_end; y += y_step) {
  84058. for (x = x_start; x !== x_end; x += x_step, i++) {
  84059. color = image[i];
  84060. imageData[(x + width * y) * 4 + 3] = 255;
  84061. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84062. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84063. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84064. }
  84065. }
  84066. return imageData;
  84067. };
  84068. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84069. var image = pixel_data;
  84070. var width = header.width, height = header.height;
  84071. var color, i = 0, x, y;
  84072. var imageData = new Uint8Array(width * height * 4);
  84073. for (y = y_start; y !== y_end; y += y_step) {
  84074. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84075. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84076. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84077. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84078. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84079. imageData[(x + width * y) * 4 + 0] = r;
  84080. imageData[(x + width * y) * 4 + 1] = g;
  84081. imageData[(x + width * y) * 4 + 2] = b;
  84082. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84083. }
  84084. }
  84085. return imageData;
  84086. };
  84087. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84088. var image = pixel_data;
  84089. var width = header.width, height = header.height;
  84090. var i = 0, x, y;
  84091. var imageData = new Uint8Array(width * height * 4);
  84092. for (y = y_start; y !== y_end; y += y_step) {
  84093. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84094. imageData[(x + width * y) * 4 + 3] = 255;
  84095. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84096. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84097. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84098. }
  84099. }
  84100. return imageData;
  84101. };
  84102. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84103. var image = pixel_data;
  84104. var width = header.width, height = header.height;
  84105. var i = 0, x, y;
  84106. var imageData = new Uint8Array(width * height * 4);
  84107. for (y = y_start; y !== y_end; y += y_step) {
  84108. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84109. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84110. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84111. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84112. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84113. }
  84114. }
  84115. return imageData;
  84116. };
  84117. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84118. var image = pixel_data;
  84119. var width = header.width, height = header.height;
  84120. var color, i = 0, x, y;
  84121. var imageData = new Uint8Array(width * height * 4);
  84122. for (y = y_start; y !== y_end; y += y_step) {
  84123. for (x = x_start; x !== x_end; x += x_step, i++) {
  84124. color = image[i];
  84125. imageData[(x + width * y) * 4 + 0] = color;
  84126. imageData[(x + width * y) * 4 + 1] = color;
  84127. imageData[(x + width * y) * 4 + 2] = color;
  84128. imageData[(x + width * y) * 4 + 3] = 255;
  84129. }
  84130. }
  84131. return imageData;
  84132. };
  84133. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84134. var image = pixel_data;
  84135. var width = header.width, height = header.height;
  84136. var i = 0, x, y;
  84137. var imageData = new Uint8Array(width * height * 4);
  84138. for (y = y_start; y !== y_end; y += y_step) {
  84139. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84140. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84141. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84142. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84143. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84144. }
  84145. }
  84146. return imageData;
  84147. };
  84148. //private static _TYPE_NO_DATA = 0;
  84149. TGATools._TYPE_INDEXED = 1;
  84150. TGATools._TYPE_RGB = 2;
  84151. TGATools._TYPE_GREY = 3;
  84152. TGATools._TYPE_RLE_INDEXED = 9;
  84153. TGATools._TYPE_RLE_RGB = 10;
  84154. TGATools._TYPE_RLE_GREY = 11;
  84155. TGATools._ORIGIN_MASK = 0x30;
  84156. TGATools._ORIGIN_SHIFT = 0x04;
  84157. TGATools._ORIGIN_BL = 0x00;
  84158. TGATools._ORIGIN_BR = 0x01;
  84159. TGATools._ORIGIN_UL = 0x02;
  84160. TGATools._ORIGIN_UR = 0x03;
  84161. return TGATools;
  84162. }());
  84163. BABYLON.TGATools = TGATools;
  84164. })(BABYLON || (BABYLON = {}));
  84165. //# sourceMappingURL=babylon.tga.js.map
  84166. var BABYLON;
  84167. (function (BABYLON) {
  84168. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84169. // All values and structures referenced from:
  84170. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84171. var DDS_MAGIC = 0x20534444;
  84172. var
  84173. //DDSD_CAPS = 0x1,
  84174. //DDSD_HEIGHT = 0x2,
  84175. //DDSD_WIDTH = 0x4,
  84176. //DDSD_PITCH = 0x8,
  84177. //DDSD_PIXELFORMAT = 0x1000,
  84178. DDSD_MIPMAPCOUNT = 0x20000;
  84179. //DDSD_LINEARSIZE = 0x80000,
  84180. //DDSD_DEPTH = 0x800000;
  84181. // var DDSCAPS_COMPLEX = 0x8,
  84182. // DDSCAPS_MIPMAP = 0x400000,
  84183. // DDSCAPS_TEXTURE = 0x1000;
  84184. var DDSCAPS2_CUBEMAP = 0x200;
  84185. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84186. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84187. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84188. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84189. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84190. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84191. // DDSCAPS2_VOLUME = 0x200000;
  84192. var
  84193. //DDPF_ALPHAPIXELS = 0x1,
  84194. //DDPF_ALPHA = 0x2,
  84195. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84196. //DDPF_YUV = 0x200,
  84197. DDPF_LUMINANCE = 0x20000;
  84198. function FourCCToInt32(value) {
  84199. return value.charCodeAt(0) +
  84200. (value.charCodeAt(1) << 8) +
  84201. (value.charCodeAt(2) << 16) +
  84202. (value.charCodeAt(3) << 24);
  84203. }
  84204. function Int32ToFourCC(value) {
  84205. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84206. }
  84207. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84208. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84209. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84210. var FOURCC_DX10 = FourCCToInt32("DX10");
  84211. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84212. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84213. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84214. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84215. var headerLengthInt = 31; // The header length in 32 bit ints
  84216. // Offsets into the header array
  84217. var off_magic = 0;
  84218. var off_size = 1;
  84219. var off_flags = 2;
  84220. var off_height = 3;
  84221. var off_width = 4;
  84222. var off_mipmapCount = 7;
  84223. var off_pfFlags = 20;
  84224. var off_pfFourCC = 21;
  84225. var off_RGBbpp = 22;
  84226. var off_RMask = 23;
  84227. var off_GMask = 24;
  84228. var off_BMask = 25;
  84229. var off_AMask = 26;
  84230. // var off_caps1 = 27;
  84231. var off_caps2 = 28;
  84232. // var off_caps3 = 29;
  84233. // var off_caps4 = 30;
  84234. var off_dxgiFormat = 32;
  84235. ;
  84236. var DDSTools = /** @class */ (function () {
  84237. function DDSTools() {
  84238. }
  84239. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84240. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84241. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84242. var mipmapCount = 1;
  84243. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84244. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84245. }
  84246. var fourCC = header[off_pfFourCC];
  84247. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84248. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84249. switch (fourCC) {
  84250. case FOURCC_D3DFMT_R16G16B16A16F:
  84251. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84252. break;
  84253. case FOURCC_D3DFMT_R32G32B32A32F:
  84254. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84255. break;
  84256. case FOURCC_DX10:
  84257. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84258. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84259. break;
  84260. }
  84261. }
  84262. return {
  84263. width: header[off_width],
  84264. height: header[off_height],
  84265. mipmapCount: mipmapCount,
  84266. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84267. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84268. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84269. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84270. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84271. dxgiFormat: dxgiFormat,
  84272. textureType: textureType
  84273. };
  84274. };
  84275. DDSTools._ToHalfFloat = function (value) {
  84276. if (!DDSTools._FloatView) {
  84277. DDSTools._FloatView = new Float32Array(1);
  84278. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84279. }
  84280. DDSTools._FloatView[0] = value;
  84281. var x = DDSTools._Int32View[0];
  84282. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84283. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84284. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84285. /* If zero, or denormal, or exponent underflows too much for a denormal
  84286. * half, return signed zero. */
  84287. if (e < 103) {
  84288. return bits;
  84289. }
  84290. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84291. if (e > 142) {
  84292. bits |= 0x7c00;
  84293. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84294. * not Inf, so make sure we set one mantissa bit too. */
  84295. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84296. return bits;
  84297. }
  84298. /* If exponent underflows but not too much, return a denormal */
  84299. if (e < 113) {
  84300. m |= 0x0800;
  84301. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84302. * to 1, which is OK. */
  84303. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84304. return bits;
  84305. }
  84306. bits |= ((e - 112) << 10) | (m >> 1);
  84307. bits += m & 1;
  84308. return bits;
  84309. };
  84310. DDSTools._FromHalfFloat = function (value) {
  84311. var s = (value & 0x8000) >> 15;
  84312. var e = (value & 0x7C00) >> 10;
  84313. var f = value & 0x03FF;
  84314. if (e === 0) {
  84315. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84316. }
  84317. else if (e == 0x1F) {
  84318. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84319. }
  84320. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84321. };
  84322. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84323. var destArray = new Float32Array(dataLength);
  84324. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84325. var index = 0;
  84326. for (var y = 0; y < height; y++) {
  84327. for (var x = 0; x < width; x++) {
  84328. var srcPos = (x + y * width) * 4;
  84329. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84330. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84331. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84332. if (DDSTools.StoreLODInAlphaChannel) {
  84333. destArray[index + 3] = lod;
  84334. }
  84335. else {
  84336. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84337. }
  84338. index += 4;
  84339. }
  84340. }
  84341. return destArray;
  84342. };
  84343. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84344. if (DDSTools.StoreLODInAlphaChannel) {
  84345. var destArray = new Uint16Array(dataLength);
  84346. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84347. var index = 0;
  84348. for (var y = 0; y < height; y++) {
  84349. for (var x = 0; x < width; x++) {
  84350. var srcPos = (x + y * width) * 4;
  84351. destArray[index] = srcData[srcPos];
  84352. destArray[index + 1] = srcData[srcPos + 1];
  84353. destArray[index + 2] = srcData[srcPos + 2];
  84354. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84355. index += 4;
  84356. }
  84357. }
  84358. return destArray;
  84359. }
  84360. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84361. };
  84362. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84363. if (DDSTools.StoreLODInAlphaChannel) {
  84364. var destArray = new Float32Array(dataLength);
  84365. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84366. var index = 0;
  84367. for (var y = 0; y < height; y++) {
  84368. for (var x = 0; x < width; x++) {
  84369. var srcPos = (x + y * width) * 4;
  84370. destArray[index] = srcData[srcPos];
  84371. destArray[index + 1] = srcData[srcPos + 1];
  84372. destArray[index + 2] = srcData[srcPos + 2];
  84373. destArray[index + 3] = lod;
  84374. index += 4;
  84375. }
  84376. }
  84377. return destArray;
  84378. }
  84379. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84380. };
  84381. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84382. var destArray = new Uint8Array(dataLength);
  84383. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84384. var index = 0;
  84385. for (var y = 0; y < height; y++) {
  84386. for (var x = 0; x < width; x++) {
  84387. var srcPos = (x + y * width) * 4;
  84388. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84389. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84390. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84391. if (DDSTools.StoreLODInAlphaChannel) {
  84392. destArray[index + 3] = lod;
  84393. }
  84394. else {
  84395. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84396. }
  84397. index += 4;
  84398. }
  84399. }
  84400. return destArray;
  84401. };
  84402. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84403. var destArray = new Uint8Array(dataLength);
  84404. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84405. var index = 0;
  84406. for (var y = 0; y < height; y++) {
  84407. for (var x = 0; x < width; x++) {
  84408. var srcPos = (x + y * width) * 4;
  84409. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84410. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84411. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84412. if (DDSTools.StoreLODInAlphaChannel) {
  84413. destArray[index + 3] = lod;
  84414. }
  84415. else {
  84416. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84417. }
  84418. index += 4;
  84419. }
  84420. }
  84421. return destArray;
  84422. };
  84423. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84424. var byteArray = new Uint8Array(dataLength);
  84425. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84426. var index = 0;
  84427. for (var y = 0; y < height; y++) {
  84428. for (var x = 0; x < width; x++) {
  84429. var srcPos = (x + y * width) * 4;
  84430. byteArray[index] = srcData[srcPos + rOffset];
  84431. byteArray[index + 1] = srcData[srcPos + gOffset];
  84432. byteArray[index + 2] = srcData[srcPos + bOffset];
  84433. byteArray[index + 3] = srcData[srcPos + aOffset];
  84434. index += 4;
  84435. }
  84436. }
  84437. return byteArray;
  84438. };
  84439. DDSTools._ExtractLongWordOrder = function (value) {
  84440. if (value === 0 || value === 255 || value === -16777216) {
  84441. return 0;
  84442. }
  84443. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84444. };
  84445. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84446. var byteArray = new Uint8Array(dataLength);
  84447. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84448. var index = 0;
  84449. for (var y = 0; y < height; y++) {
  84450. for (var x = 0; x < width; x++) {
  84451. var srcPos = (x + y * width) * 3;
  84452. byteArray[index] = srcData[srcPos + rOffset];
  84453. byteArray[index + 1] = srcData[srcPos + gOffset];
  84454. byteArray[index + 2] = srcData[srcPos + bOffset];
  84455. index += 3;
  84456. }
  84457. }
  84458. return byteArray;
  84459. };
  84460. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84461. var byteArray = new Uint8Array(dataLength);
  84462. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84463. var index = 0;
  84464. for (var y = 0; y < height; y++) {
  84465. for (var x = 0; x < width; x++) {
  84466. var srcPos = (x + y * width);
  84467. byteArray[index] = srcData[srcPos];
  84468. index++;
  84469. }
  84470. }
  84471. return byteArray;
  84472. };
  84473. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84474. if (lodIndex === void 0) { lodIndex = -1; }
  84475. var sphericalPolynomialFaces = null;
  84476. if (info.sphericalPolynomial) {
  84477. sphericalPolynomialFaces = new Array();
  84478. }
  84479. var ext = engine.getCaps().s3tc;
  84480. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84481. var fourCC, width, height, dataLength = 0, dataOffset;
  84482. var byteArray, mipmapCount, mip;
  84483. var internalFormat = 0;
  84484. var format = 0;
  84485. var blockBytes = 1;
  84486. if (header[off_magic] !== DDS_MAGIC) {
  84487. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84488. return;
  84489. }
  84490. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84491. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84492. return;
  84493. }
  84494. if (info.isCompressed && !ext) {
  84495. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84496. return;
  84497. }
  84498. var bpp = header[off_RGBbpp];
  84499. dataOffset = header[off_size] + 4;
  84500. var computeFormats = false;
  84501. if (info.isFourCC) {
  84502. fourCC = header[off_pfFourCC];
  84503. switch (fourCC) {
  84504. case FOURCC_DXT1:
  84505. blockBytes = 8;
  84506. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84507. break;
  84508. case FOURCC_DXT3:
  84509. blockBytes = 16;
  84510. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84511. break;
  84512. case FOURCC_DXT5:
  84513. blockBytes = 16;
  84514. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84515. break;
  84516. case FOURCC_D3DFMT_R16G16B16A16F:
  84517. computeFormats = true;
  84518. break;
  84519. case FOURCC_D3DFMT_R32G32B32A32F:
  84520. computeFormats = true;
  84521. break;
  84522. case FOURCC_DX10:
  84523. // There is an additionnal header so dataOffset need to be changed
  84524. dataOffset += 5 * 4; // 5 uints
  84525. var supported = false;
  84526. switch (info.dxgiFormat) {
  84527. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84528. computeFormats = true;
  84529. supported = true;
  84530. break;
  84531. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84532. info.isRGB = true;
  84533. info.isFourCC = false;
  84534. bpp = 32;
  84535. supported = true;
  84536. break;
  84537. }
  84538. if (supported) {
  84539. break;
  84540. }
  84541. default:
  84542. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84543. return;
  84544. }
  84545. }
  84546. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84547. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84548. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84549. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84550. if (computeFormats) {
  84551. format = engine._getWebGLTextureType(info.textureType);
  84552. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84553. }
  84554. mipmapCount = 1;
  84555. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84556. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84557. }
  84558. for (var face = 0; face < faces; face++) {
  84559. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84560. width = header[off_width];
  84561. height = header[off_height];
  84562. for (mip = 0; mip < mipmapCount; ++mip) {
  84563. if (lodIndex === -1 || lodIndex === mip) {
  84564. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84565. var i = (lodIndex === -1) ? mip : 0;
  84566. if (!info.isCompressed && info.isFourCC) {
  84567. dataLength = width * height * 4;
  84568. var floatArray = null;
  84569. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84570. if (bpp === 128) {
  84571. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84572. if (sphericalPolynomialFaces && i == 0) {
  84573. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84574. }
  84575. }
  84576. else if (bpp === 64) {
  84577. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84578. if (sphericalPolynomialFaces && i == 0) {
  84579. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84580. }
  84581. }
  84582. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84583. format = engine._getWebGLTextureType(info.textureType);
  84584. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84585. }
  84586. else {
  84587. if (bpp === 128) {
  84588. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84589. if (sphericalPolynomialFaces && i == 0) {
  84590. sphericalPolynomialFaces.push(floatArray);
  84591. }
  84592. }
  84593. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84594. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84595. if (sphericalPolynomialFaces && i == 0) {
  84596. sphericalPolynomialFaces.push(floatArray);
  84597. }
  84598. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84599. format = engine._getWebGLTextureType(info.textureType);
  84600. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84601. }
  84602. else { // 64
  84603. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84604. if (sphericalPolynomialFaces && i == 0) {
  84605. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84606. }
  84607. }
  84608. }
  84609. if (floatArray) {
  84610. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84611. }
  84612. }
  84613. else if (info.isRGB) {
  84614. if (bpp === 24) {
  84615. dataLength = width * height * 3;
  84616. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84617. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84618. }
  84619. else { // 32
  84620. dataLength = width * height * 4;
  84621. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84622. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84623. }
  84624. }
  84625. else if (info.isLuminance) {
  84626. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84627. var unpaddedRowSize = width;
  84628. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84629. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84630. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84631. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84632. }
  84633. else {
  84634. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84635. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84636. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84637. }
  84638. }
  84639. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84640. width *= 0.5;
  84641. height *= 0.5;
  84642. width = Math.max(1.0, width);
  84643. height = Math.max(1.0, height);
  84644. }
  84645. if (currentFace !== undefined) {
  84646. // Loading a single face
  84647. break;
  84648. }
  84649. }
  84650. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84651. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84652. size: header[off_width],
  84653. right: sphericalPolynomialFaces[0],
  84654. left: sphericalPolynomialFaces[1],
  84655. up: sphericalPolynomialFaces[2],
  84656. down: sphericalPolynomialFaces[3],
  84657. front: sphericalPolynomialFaces[4],
  84658. back: sphericalPolynomialFaces[5],
  84659. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84660. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84661. gammaSpace: false,
  84662. });
  84663. }
  84664. else {
  84665. info.sphericalPolynomial = undefined;
  84666. }
  84667. };
  84668. DDSTools.StoreLODInAlphaChannel = false;
  84669. return DDSTools;
  84670. }());
  84671. BABYLON.DDSTools = DDSTools;
  84672. })(BABYLON || (BABYLON = {}));
  84673. //# sourceMappingURL=babylon.dds.js.map
  84674. var BABYLON;
  84675. (function (BABYLON) {
  84676. /**
  84677. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84678. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84679. */
  84680. var KhronosTextureContainer = /** @class */ (function () {
  84681. /**
  84682. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84683. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84684. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84685. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84686. */
  84687. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84688. this.arrayBuffer = arrayBuffer;
  84689. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84690. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84691. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84692. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84693. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84694. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84695. BABYLON.Tools.Error("texture missing KTX identifier");
  84696. return;
  84697. }
  84698. // load the reset of the header in native 32 bit int
  84699. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84700. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84701. var oppositeEndianess = header[0] === 0x01020304;
  84702. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84703. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84704. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84705. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84706. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84707. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84708. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84709. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84710. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84711. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84712. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84713. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84714. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84715. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84716. if (this.glType !== 0) {
  84717. BABYLON.Tools.Error("only compressed formats currently supported");
  84718. return;
  84719. }
  84720. else {
  84721. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84722. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84723. }
  84724. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84725. BABYLON.Tools.Error("only 2D textures currently supported");
  84726. return;
  84727. }
  84728. if (this.numberOfArrayElements !== 0) {
  84729. BABYLON.Tools.Error("texture arrays not currently supported");
  84730. return;
  84731. }
  84732. if (this.numberOfFaces !== facesExpected) {
  84733. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84734. return;
  84735. }
  84736. // we now have a completely validated file, so could use existence of loadType as success
  84737. // would need to make this more elaborate & adjust checks above to support more than one load type
  84738. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84739. }
  84740. // not as fast hardware based, but will probably never need to use
  84741. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84742. return ((val & 0xFF) << 24)
  84743. | ((val & 0xFF00) << 8)
  84744. | ((val >> 8) & 0xFF00)
  84745. | ((val >> 24) & 0xFF);
  84746. };
  84747. /**
  84748. * It is assumed that the texture has already been created & is currently bound
  84749. */
  84750. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84751. switch (this.loadType) {
  84752. case KhronosTextureContainer.COMPRESSED_2D:
  84753. this._upload2DCompressedLevels(gl, loadMipmaps);
  84754. break;
  84755. case KhronosTextureContainer.TEX_2D:
  84756. case KhronosTextureContainer.COMPRESSED_3D:
  84757. case KhronosTextureContainer.TEX_3D:
  84758. }
  84759. };
  84760. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84761. // initialize width & height for level 1
  84762. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84763. var width = this.pixelWidth;
  84764. var height = this.pixelHeight;
  84765. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84766. for (var level = 0; level < mipmapCount; level++) {
  84767. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84768. for (var face = 0; face < this.numberOfFaces; face++) {
  84769. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84770. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84771. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84772. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84773. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84774. }
  84775. width = Math.max(1.0, width * 0.5);
  84776. height = Math.max(1.0, height * 0.5);
  84777. }
  84778. };
  84779. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84780. // load types
  84781. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84782. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84783. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84784. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84785. return KhronosTextureContainer;
  84786. }());
  84787. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84788. })(BABYLON || (BABYLON = {}));
  84789. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84790. var BABYLON;
  84791. (function (BABYLON) {
  84792. var Debug;
  84793. (function (Debug) {
  84794. /**
  84795. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84796. */
  84797. var SkeletonViewer = /** @class */ (function () {
  84798. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84799. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84800. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84801. this.skeleton = skeleton;
  84802. this.mesh = mesh;
  84803. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84804. this.renderingGroupId = renderingGroupId;
  84805. this.color = BABYLON.Color3.White();
  84806. this._debugLines = new Array();
  84807. this._isEnabled = false;
  84808. this._scene = scene;
  84809. this.update();
  84810. this._renderFunction = this.update.bind(this);
  84811. }
  84812. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84813. get: function () {
  84814. return this._isEnabled;
  84815. },
  84816. set: function (value) {
  84817. if (this._isEnabled === value) {
  84818. return;
  84819. }
  84820. this._isEnabled = value;
  84821. if (value) {
  84822. this._scene.registerBeforeRender(this._renderFunction);
  84823. }
  84824. else {
  84825. this._scene.unregisterBeforeRender(this._renderFunction);
  84826. }
  84827. },
  84828. enumerable: true,
  84829. configurable: true
  84830. });
  84831. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84832. if (x === void 0) { x = 0; }
  84833. if (y === void 0) { y = 0; }
  84834. if (z === void 0) { z = 0; }
  84835. var tmat = BABYLON.Tmp.Matrix[0];
  84836. var parentBone = bone.getParent();
  84837. tmat.copyFrom(bone.getLocalMatrix());
  84838. if (x !== 0 || y !== 0 || z !== 0) {
  84839. var tmat2 = BABYLON.Tmp.Matrix[1];
  84840. BABYLON.Matrix.IdentityToRef(tmat2);
  84841. tmat2.m[12] = x;
  84842. tmat2.m[13] = y;
  84843. tmat2.m[14] = z;
  84844. tmat2.multiplyToRef(tmat, tmat);
  84845. }
  84846. if (parentBone) {
  84847. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84848. }
  84849. tmat.multiplyToRef(meshMat, tmat);
  84850. position.x = tmat.m[12];
  84851. position.y = tmat.m[13];
  84852. position.z = tmat.m[14];
  84853. };
  84854. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84855. var len = bones.length;
  84856. var meshPos = this.mesh.position;
  84857. for (var i = 0; i < len; i++) {
  84858. var bone = bones[i];
  84859. var points = this._debugLines[i];
  84860. if (!points) {
  84861. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84862. this._debugLines[i] = points;
  84863. }
  84864. this._getBonePosition(points[0], bone, meshMat);
  84865. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84866. points[0].subtractInPlace(meshPos);
  84867. points[1].subtractInPlace(meshPos);
  84868. }
  84869. };
  84870. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84871. var len = bones.length;
  84872. var boneNum = 0;
  84873. var meshPos = this.mesh.position;
  84874. for (var i = len - 1; i >= 0; i--) {
  84875. var childBone = bones[i];
  84876. var parentBone = childBone.getParent();
  84877. if (!parentBone) {
  84878. continue;
  84879. }
  84880. var points = this._debugLines[boneNum];
  84881. if (!points) {
  84882. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84883. this._debugLines[boneNum] = points;
  84884. }
  84885. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84886. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84887. points[0].subtractInPlace(meshPos);
  84888. points[1].subtractInPlace(meshPos);
  84889. boneNum++;
  84890. }
  84891. };
  84892. SkeletonViewer.prototype.update = function () {
  84893. if (this.autoUpdateBonesMatrices) {
  84894. this.skeleton.computeAbsoluteTransforms();
  84895. }
  84896. if (this.skeleton.bones[0].length === undefined) {
  84897. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84898. }
  84899. else {
  84900. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84901. }
  84902. if (!this._debugMesh) {
  84903. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84904. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84905. }
  84906. else {
  84907. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84908. }
  84909. this._debugMesh.position.copyFrom(this.mesh.position);
  84910. this._debugMesh.color = this.color;
  84911. };
  84912. SkeletonViewer.prototype.dispose = function () {
  84913. if (this._debugMesh) {
  84914. this.isEnabled = false;
  84915. this._debugMesh.dispose();
  84916. this._debugMesh = null;
  84917. }
  84918. };
  84919. return SkeletonViewer;
  84920. }());
  84921. Debug.SkeletonViewer = SkeletonViewer;
  84922. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84923. })(BABYLON || (BABYLON = {}));
  84924. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84925. /**
  84926. * Module Debug contains the (visual) components to debug a scene correctly
  84927. */
  84928. var BABYLON;
  84929. (function (BABYLON) {
  84930. var Debug;
  84931. (function (Debug) {
  84932. /**
  84933. * The Axes viewer will show 3 axes in a specific point in space
  84934. */
  84935. var AxesViewer = /** @class */ (function () {
  84936. function AxesViewer(scene, scaleLines) {
  84937. if (scaleLines === void 0) { scaleLines = 1; }
  84938. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84939. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84940. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84941. this.scaleLines = 1;
  84942. this.scaleLines = scaleLines;
  84943. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84944. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84945. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84946. this._xmesh.renderingGroupId = 2;
  84947. this._ymesh.renderingGroupId = 2;
  84948. this._zmesh.renderingGroupId = 2;
  84949. this._xmesh.material.checkReadyOnlyOnce = true;
  84950. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84951. this._ymesh.material.checkReadyOnlyOnce = true;
  84952. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84953. this._zmesh.material.checkReadyOnlyOnce = true;
  84954. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84955. this.scene = scene;
  84956. }
  84957. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84958. var scaleLines = this.scaleLines;
  84959. if (this._xmesh) {
  84960. this._xmesh.position.copyFrom(position);
  84961. }
  84962. if (this._ymesh) {
  84963. this._ymesh.position.copyFrom(position);
  84964. }
  84965. if (this._zmesh) {
  84966. this._zmesh.position.copyFrom(position);
  84967. }
  84968. var point2 = this._xline[1];
  84969. point2.x = xaxis.x * scaleLines;
  84970. point2.y = xaxis.y * scaleLines;
  84971. point2.z = xaxis.z * scaleLines;
  84972. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84973. point2 = this._yline[1];
  84974. point2.x = yaxis.x * scaleLines;
  84975. point2.y = yaxis.y * scaleLines;
  84976. point2.z = yaxis.z * scaleLines;
  84977. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84978. point2 = this._zline[1];
  84979. point2.x = zaxis.x * scaleLines;
  84980. point2.y = zaxis.y * scaleLines;
  84981. point2.z = zaxis.z * scaleLines;
  84982. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84983. };
  84984. AxesViewer.prototype.dispose = function () {
  84985. if (this._xmesh) {
  84986. this._xmesh.dispose();
  84987. }
  84988. if (this._ymesh) {
  84989. this._ymesh.dispose();
  84990. }
  84991. if (this._zmesh) {
  84992. this._zmesh.dispose();
  84993. }
  84994. this._xmesh = null;
  84995. this._ymesh = null;
  84996. this._zmesh = null;
  84997. this.scene = null;
  84998. };
  84999. return AxesViewer;
  85000. }());
  85001. Debug.AxesViewer = AxesViewer;
  85002. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85003. })(BABYLON || (BABYLON = {}));
  85004. //# sourceMappingURL=babylon.axesViewer.js.map
  85005. var BABYLON;
  85006. (function (BABYLON) {
  85007. var Debug;
  85008. (function (Debug) {
  85009. /**
  85010. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85011. */
  85012. var BoneAxesViewer = /** @class */ (function (_super) {
  85013. __extends(BoneAxesViewer, _super);
  85014. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85015. if (scaleLines === void 0) { scaleLines = 1; }
  85016. var _this = _super.call(this, scene, scaleLines) || this;
  85017. _this.pos = BABYLON.Vector3.Zero();
  85018. _this.xaxis = BABYLON.Vector3.Zero();
  85019. _this.yaxis = BABYLON.Vector3.Zero();
  85020. _this.zaxis = BABYLON.Vector3.Zero();
  85021. _this.mesh = mesh;
  85022. _this.bone = bone;
  85023. return _this;
  85024. }
  85025. BoneAxesViewer.prototype.update = function () {
  85026. if (!this.mesh || !this.bone) {
  85027. return;
  85028. }
  85029. var bone = this.bone;
  85030. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85031. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85032. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85033. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85034. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85035. };
  85036. BoneAxesViewer.prototype.dispose = function () {
  85037. if (this.mesh) {
  85038. this.mesh = null;
  85039. this.bone = null;
  85040. _super.prototype.dispose.call(this);
  85041. }
  85042. };
  85043. return BoneAxesViewer;
  85044. }(Debug.AxesViewer));
  85045. Debug.BoneAxesViewer = BoneAxesViewer;
  85046. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85047. })(BABYLON || (BABYLON = {}));
  85048. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85049. var BABYLON;
  85050. (function (BABYLON) {
  85051. var RayHelper = /** @class */ (function () {
  85052. function RayHelper(ray) {
  85053. this.ray = ray;
  85054. }
  85055. RayHelper.CreateAndShow = function (ray, scene, color) {
  85056. var helper = new RayHelper(ray);
  85057. helper.show(scene, color);
  85058. return helper;
  85059. };
  85060. RayHelper.prototype.show = function (scene, color) {
  85061. if (!this._renderFunction && this.ray) {
  85062. var ray = this.ray;
  85063. this._renderFunction = this._render.bind(this);
  85064. this._scene = scene;
  85065. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85066. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85067. if (this._renderFunction) {
  85068. this._scene.registerBeforeRender(this._renderFunction);
  85069. }
  85070. }
  85071. if (color && this._renderLine) {
  85072. this._renderLine.color.copyFrom(color);
  85073. }
  85074. };
  85075. RayHelper.prototype.hide = function () {
  85076. if (this._renderFunction && this._scene) {
  85077. this._scene.unregisterBeforeRender(this._renderFunction);
  85078. this._scene = null;
  85079. this._renderFunction = null;
  85080. if (this._renderLine) {
  85081. this._renderLine.dispose();
  85082. this._renderLine = null;
  85083. }
  85084. this._renderPoints = [];
  85085. }
  85086. };
  85087. RayHelper.prototype._render = function () {
  85088. var ray = this.ray;
  85089. if (!ray) {
  85090. return;
  85091. }
  85092. var point = this._renderPoints[1];
  85093. var len = Math.min(ray.length, 1000000);
  85094. point.copyFrom(ray.direction);
  85095. point.scaleInPlace(len);
  85096. point.addInPlace(ray.origin);
  85097. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85098. };
  85099. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85100. this._attachedToMesh = mesh;
  85101. var ray = this.ray;
  85102. if (!ray) {
  85103. return;
  85104. }
  85105. if (!ray.direction) {
  85106. ray.direction = BABYLON.Vector3.Zero();
  85107. }
  85108. if (!ray.origin) {
  85109. ray.origin = BABYLON.Vector3.Zero();
  85110. }
  85111. if (length) {
  85112. ray.length = length;
  85113. }
  85114. if (!meshSpaceOrigin) {
  85115. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85116. }
  85117. if (!meshSpaceDirection) {
  85118. // -1 so that this will work with Mesh.lookAt
  85119. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85120. }
  85121. if (!this._meshSpaceDirection) {
  85122. this._meshSpaceDirection = meshSpaceDirection.clone();
  85123. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85124. }
  85125. else {
  85126. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85127. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85128. }
  85129. if (!this._updateToMeshFunction) {
  85130. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85131. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85132. }
  85133. this._updateToMesh();
  85134. };
  85135. RayHelper.prototype.detachFromMesh = function () {
  85136. if (this._attachedToMesh) {
  85137. if (this._updateToMeshFunction) {
  85138. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85139. }
  85140. this._attachedToMesh = null;
  85141. this._updateToMeshFunction = null;
  85142. }
  85143. };
  85144. RayHelper.prototype._updateToMesh = function () {
  85145. var ray = this.ray;
  85146. if (!this._attachedToMesh || !ray) {
  85147. return;
  85148. }
  85149. if (this._attachedToMesh._isDisposed) {
  85150. this.detachFromMesh();
  85151. return;
  85152. }
  85153. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85154. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85155. };
  85156. RayHelper.prototype.dispose = function () {
  85157. this.hide();
  85158. this.detachFromMesh();
  85159. this.ray = null;
  85160. };
  85161. return RayHelper;
  85162. }());
  85163. BABYLON.RayHelper = RayHelper;
  85164. })(BABYLON || (BABYLON = {}));
  85165. //# sourceMappingURL=babylon.rayHelper.js.map
  85166. var BABYLON;
  85167. (function (BABYLON) {
  85168. // load the inspector using require, if not present in the global namespace.
  85169. var DebugLayer = /** @class */ (function () {
  85170. function DebugLayer(scene) {
  85171. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85172. this._scene = scene;
  85173. // load inspector using require, if it doesn't exist on the global namespace.
  85174. }
  85175. /** Creates the inspector window. */
  85176. DebugLayer.prototype._createInspector = function (config) {
  85177. if (config === void 0) { config = {}; }
  85178. var popup = config.popup || false;
  85179. var initialTab = config.initialTab || 0;
  85180. var parentElement = config.parentElement || null;
  85181. if (!this._inspector) {
  85182. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85183. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85184. } // else nothing to do,; instance is already existing
  85185. };
  85186. DebugLayer.prototype.isVisible = function () {
  85187. if (!this._inspector) {
  85188. return false;
  85189. }
  85190. return true;
  85191. };
  85192. DebugLayer.prototype.hide = function () {
  85193. if (this._inspector) {
  85194. try {
  85195. this._inspector.dispose();
  85196. }
  85197. catch (e) {
  85198. // If the inspector has been removed directly from the inspector tool
  85199. }
  85200. this._inspector = null;
  85201. }
  85202. };
  85203. DebugLayer.prototype.show = function (config) {
  85204. if (config === void 0) { config = {}; }
  85205. if (typeof this.BJSINSPECTOR == 'undefined') {
  85206. // Load inspector and add it to the DOM
  85207. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85208. }
  85209. else {
  85210. // Otherwise creates the inspector
  85211. this._createInspector(config);
  85212. }
  85213. };
  85214. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85215. return DebugLayer;
  85216. }());
  85217. BABYLON.DebugLayer = DebugLayer;
  85218. })(BABYLON || (BABYLON = {}));
  85219. //# sourceMappingURL=babylon.debugLayer.js.map
  85220. var BABYLON;
  85221. (function (BABYLON) {
  85222. var Debug;
  85223. (function (Debug) {
  85224. /**
  85225. * Used to show the physics impostor around the specific mesh.
  85226. */
  85227. var PhysicsViewer = /** @class */ (function () {
  85228. function PhysicsViewer(scene) {
  85229. this._impostors = [];
  85230. this._meshes = [];
  85231. this._numMeshes = 0;
  85232. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85233. var physicEngine = this._scene.getPhysicsEngine();
  85234. if (physicEngine) {
  85235. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85236. }
  85237. }
  85238. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85239. var plugin = this._physicsEnginePlugin;
  85240. for (var i = 0; i < this._numMeshes; i++) {
  85241. var impostor = this._impostors[i];
  85242. if (!impostor) {
  85243. continue;
  85244. }
  85245. if (impostor.isDisposed) {
  85246. this.hideImpostor(this._impostors[i--]);
  85247. }
  85248. else {
  85249. var mesh = this._meshes[i];
  85250. if (mesh && plugin) {
  85251. plugin.syncMeshWithImpostor(mesh, impostor);
  85252. }
  85253. }
  85254. }
  85255. };
  85256. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85257. if (!this._scene) {
  85258. return;
  85259. }
  85260. for (var i = 0; i < this._numMeshes; i++) {
  85261. if (this._impostors[i] == impostor) {
  85262. return;
  85263. }
  85264. }
  85265. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85266. if (debugMesh) {
  85267. this._impostors[this._numMeshes] = impostor;
  85268. this._meshes[this._numMeshes] = debugMesh;
  85269. if (this._numMeshes === 0) {
  85270. this._renderFunction = this._updateDebugMeshes.bind(this);
  85271. this._scene.registerBeforeRender(this._renderFunction);
  85272. }
  85273. this._numMeshes++;
  85274. }
  85275. };
  85276. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85277. if (!impostor || !this._scene) {
  85278. return;
  85279. }
  85280. var removed = false;
  85281. for (var i = 0; i < this._numMeshes; i++) {
  85282. if (this._impostors[i] == impostor) {
  85283. var mesh = this._meshes[i];
  85284. if (!mesh) {
  85285. continue;
  85286. }
  85287. this._scene.removeMesh(mesh);
  85288. mesh.dispose();
  85289. this._numMeshes--;
  85290. if (this._numMeshes > 0) {
  85291. this._meshes[i] = this._meshes[this._numMeshes];
  85292. this._impostors[i] = this._impostors[this._numMeshes];
  85293. this._meshes[this._numMeshes] = null;
  85294. this._impostors[this._numMeshes] = null;
  85295. }
  85296. else {
  85297. this._meshes[0] = null;
  85298. this._impostors[0] = null;
  85299. }
  85300. removed = true;
  85301. break;
  85302. }
  85303. }
  85304. if (removed && this._numMeshes === 0) {
  85305. this._scene.unregisterBeforeRender(this._renderFunction);
  85306. }
  85307. };
  85308. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85309. if (!this._debugMaterial) {
  85310. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85311. this._debugMaterial.wireframe = true;
  85312. }
  85313. return this._debugMaterial;
  85314. };
  85315. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85316. if (!this._debugBoxMesh) {
  85317. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85318. this._debugBoxMesh.renderingGroupId = 1;
  85319. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85320. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85321. scene.removeMesh(this._debugBoxMesh);
  85322. }
  85323. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85324. };
  85325. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85326. if (!this._debugSphereMesh) {
  85327. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85328. this._debugSphereMesh.renderingGroupId = 1;
  85329. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85330. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85331. scene.removeMesh(this._debugSphereMesh);
  85332. }
  85333. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85334. };
  85335. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85336. var mesh = null;
  85337. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85338. mesh = this._getDebugBoxMesh(scene);
  85339. impostor.getBoxSizeToRef(mesh.scaling);
  85340. }
  85341. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85342. mesh = this._getDebugSphereMesh(scene);
  85343. var radius = impostor.getRadius();
  85344. mesh.scaling.x = radius * 2;
  85345. mesh.scaling.y = radius * 2;
  85346. mesh.scaling.z = radius * 2;
  85347. }
  85348. return mesh;
  85349. };
  85350. PhysicsViewer.prototype.dispose = function () {
  85351. for (var i = 0; i < this._numMeshes; i++) {
  85352. this.hideImpostor(this._impostors[i]);
  85353. }
  85354. if (this._debugBoxMesh) {
  85355. this._debugBoxMesh.dispose();
  85356. }
  85357. if (this._debugSphereMesh) {
  85358. this._debugSphereMesh.dispose();
  85359. }
  85360. if (this._debugMaterial) {
  85361. this._debugMaterial.dispose();
  85362. }
  85363. this._impostors.length = 0;
  85364. this._scene = null;
  85365. this._physicsEnginePlugin = null;
  85366. };
  85367. return PhysicsViewer;
  85368. }());
  85369. Debug.PhysicsViewer = PhysicsViewer;
  85370. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85371. })(BABYLON || (BABYLON = {}));
  85372. //# sourceMappingURL=babylon.physicsViewer.js.map
  85373. var BABYLON;
  85374. (function (BABYLON) {
  85375. var BoundingBoxRenderer = /** @class */ (function () {
  85376. function BoundingBoxRenderer(scene) {
  85377. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85378. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85379. this.showBackLines = true;
  85380. this.renderList = new BABYLON.SmartArray(32);
  85381. this._vertexBuffers = {};
  85382. this._scene = scene;
  85383. }
  85384. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85385. if (this._colorShader) {
  85386. return;
  85387. }
  85388. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85389. attributes: [BABYLON.VertexBuffer.PositionKind],
  85390. uniforms: ["world", "viewProjection", "color"]
  85391. });
  85392. var engine = this._scene.getEngine();
  85393. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85394. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85395. this._createIndexBuffer();
  85396. };
  85397. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85398. var engine = this._scene.getEngine();
  85399. 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]);
  85400. };
  85401. BoundingBoxRenderer.prototype._rebuild = function () {
  85402. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85403. if (vb) {
  85404. vb._rebuild();
  85405. }
  85406. this._createIndexBuffer();
  85407. };
  85408. BoundingBoxRenderer.prototype.reset = function () {
  85409. this.renderList.reset();
  85410. };
  85411. BoundingBoxRenderer.prototype.render = function () {
  85412. if (this.renderList.length === 0) {
  85413. return;
  85414. }
  85415. this._prepareRessources();
  85416. if (!this._colorShader.isReady()) {
  85417. return;
  85418. }
  85419. var engine = this._scene.getEngine();
  85420. engine.setDepthWrite(false);
  85421. this._colorShader._preBind();
  85422. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85423. var boundingBox = this.renderList.data[boundingBoxIndex];
  85424. var min = boundingBox.minimum;
  85425. var max = boundingBox.maximum;
  85426. var diff = max.subtract(min);
  85427. var median = min.add(diff.scale(0.5));
  85428. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85429. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85430. .multiply(boundingBox.getWorldMatrix());
  85431. // VBOs
  85432. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85433. if (this.showBackLines) {
  85434. // Back
  85435. engine.setDepthFunctionToGreaterOrEqual();
  85436. this._scene.resetCachedMaterial();
  85437. this._colorShader.setColor4("color", this.backColor.toColor4());
  85438. this._colorShader.bind(worldMatrix);
  85439. // Draw order
  85440. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85441. }
  85442. // Front
  85443. engine.setDepthFunctionToLess();
  85444. this._scene.resetCachedMaterial();
  85445. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85446. this._colorShader.bind(worldMatrix);
  85447. // Draw order
  85448. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85449. }
  85450. this._colorShader.unbind();
  85451. engine.setDepthFunctionToLessOrEqual();
  85452. engine.setDepthWrite(true);
  85453. };
  85454. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85455. this._prepareRessources();
  85456. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85457. return;
  85458. }
  85459. var engine = this._scene.getEngine();
  85460. engine.setDepthWrite(false);
  85461. engine.setColorWrite(false);
  85462. this._colorShader._preBind();
  85463. var boundingBox = mesh._boundingInfo.boundingBox;
  85464. var min = boundingBox.minimum;
  85465. var max = boundingBox.maximum;
  85466. var diff = max.subtract(min);
  85467. var median = min.add(diff.scale(0.5));
  85468. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85469. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85470. .multiply(boundingBox.getWorldMatrix());
  85471. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85472. engine.setDepthFunctionToLess();
  85473. this._scene.resetCachedMaterial();
  85474. this._colorShader.bind(worldMatrix);
  85475. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85476. this._colorShader.unbind();
  85477. engine.setDepthFunctionToLessOrEqual();
  85478. engine.setDepthWrite(true);
  85479. engine.setColorWrite(true);
  85480. };
  85481. BoundingBoxRenderer.prototype.dispose = function () {
  85482. if (!this._colorShader) {
  85483. return;
  85484. }
  85485. this.renderList.dispose();
  85486. this._colorShader.dispose();
  85487. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85488. if (buffer) {
  85489. buffer.dispose();
  85490. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85491. }
  85492. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85493. };
  85494. return BoundingBoxRenderer;
  85495. }());
  85496. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85497. })(BABYLON || (BABYLON = {}));
  85498. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85499. var BABYLON;
  85500. (function (BABYLON) {
  85501. /**
  85502. * Defines a target to use with MorphTargetManager
  85503. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85504. */
  85505. var MorphTarget = /** @class */ (function () {
  85506. /**
  85507. * Creates a new MorphTarget
  85508. * @param name defines the name of the target
  85509. * @param influence defines the influence to use
  85510. */
  85511. function MorphTarget(
  85512. /** defines the name of the target */
  85513. name, influence, scene) {
  85514. if (influence === void 0) { influence = 0; }
  85515. if (scene === void 0) { scene = null; }
  85516. this.name = name;
  85517. /**
  85518. * Gets or sets the list of animations
  85519. */
  85520. this.animations = new Array();
  85521. this._positions = null;
  85522. this._normals = null;
  85523. this._tangents = null;
  85524. /**
  85525. * Observable raised when the influence changes
  85526. */
  85527. this.onInfluenceChanged = new BABYLON.Observable();
  85528. this._animationPropertiesOverride = null;
  85529. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85530. this.influence = influence;
  85531. }
  85532. Object.defineProperty(MorphTarget.prototype, "influence", {
  85533. /**
  85534. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85535. */
  85536. get: function () {
  85537. return this._influence;
  85538. },
  85539. set: function (influence) {
  85540. if (this._influence === influence) {
  85541. return;
  85542. }
  85543. var previous = this._influence;
  85544. this._influence = influence;
  85545. if (this.onInfluenceChanged.hasObservers) {
  85546. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85547. }
  85548. },
  85549. enumerable: true,
  85550. configurable: true
  85551. });
  85552. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85553. /**
  85554. * Gets or sets the animation properties override
  85555. */
  85556. get: function () {
  85557. if (!this._animationPropertiesOverride && this._scene) {
  85558. return this._scene.animationPropertiesOverride;
  85559. }
  85560. return this._animationPropertiesOverride;
  85561. },
  85562. set: function (value) {
  85563. this._animationPropertiesOverride = value;
  85564. },
  85565. enumerable: true,
  85566. configurable: true
  85567. });
  85568. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85569. /**
  85570. * Gets a boolean defining if the target contains position data
  85571. */
  85572. get: function () {
  85573. return !!this._positions;
  85574. },
  85575. enumerable: true,
  85576. configurable: true
  85577. });
  85578. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85579. /**
  85580. * Gets a boolean defining if the target contains normal data
  85581. */
  85582. get: function () {
  85583. return !!this._normals;
  85584. },
  85585. enumerable: true,
  85586. configurable: true
  85587. });
  85588. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85589. /**
  85590. * Gets a boolean defining if the target contains tangent data
  85591. */
  85592. get: function () {
  85593. return !!this._tangents;
  85594. },
  85595. enumerable: true,
  85596. configurable: true
  85597. });
  85598. /**
  85599. * Affects position data to this target
  85600. * @param data defines the position data to use
  85601. */
  85602. MorphTarget.prototype.setPositions = function (data) {
  85603. this._positions = data;
  85604. };
  85605. /**
  85606. * Gets the position data stored in this target
  85607. * @returns a FloatArray containing the position data (or null if not present)
  85608. */
  85609. MorphTarget.prototype.getPositions = function () {
  85610. return this._positions;
  85611. };
  85612. /**
  85613. * Affects normal data to this target
  85614. * @param data defines the normal data to use
  85615. */
  85616. MorphTarget.prototype.setNormals = function (data) {
  85617. this._normals = data;
  85618. };
  85619. /**
  85620. * Gets the normal data stored in this target
  85621. * @returns a FloatArray containing the normal data (or null if not present)
  85622. */
  85623. MorphTarget.prototype.getNormals = function () {
  85624. return this._normals;
  85625. };
  85626. /**
  85627. * Affects tangent data to this target
  85628. * @param data defines the tangent data to use
  85629. */
  85630. MorphTarget.prototype.setTangents = function (data) {
  85631. this._tangents = data;
  85632. };
  85633. /**
  85634. * Gets the tangent data stored in this target
  85635. * @returns a FloatArray containing the tangent data (or null if not present)
  85636. */
  85637. MorphTarget.prototype.getTangents = function () {
  85638. return this._tangents;
  85639. };
  85640. /**
  85641. * Serializes the current target into a Serialization object
  85642. * @returns the serialized object
  85643. */
  85644. MorphTarget.prototype.serialize = function () {
  85645. var serializationObject = {};
  85646. serializationObject.name = this.name;
  85647. serializationObject.influence = this.influence;
  85648. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85649. if (this.hasNormals) {
  85650. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85651. }
  85652. if (this.hasTangents) {
  85653. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85654. }
  85655. // Animations
  85656. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85657. return serializationObject;
  85658. };
  85659. // Statics
  85660. /**
  85661. * Creates a new target from serialized data
  85662. * @param serializationObject defines the serialized data to use
  85663. * @returns a new MorphTarget
  85664. */
  85665. MorphTarget.Parse = function (serializationObject) {
  85666. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85667. result.setPositions(serializationObject.positions);
  85668. if (serializationObject.normals) {
  85669. result.setNormals(serializationObject.normals);
  85670. }
  85671. if (serializationObject.tangents) {
  85672. result.setTangents(serializationObject.tangents);
  85673. }
  85674. // Animations
  85675. if (serializationObject.animations) {
  85676. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85677. var parsedAnimation = serializationObject.animations[animationIndex];
  85678. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85679. }
  85680. }
  85681. return result;
  85682. };
  85683. /**
  85684. * Creates a MorphTarget from mesh data
  85685. * @param mesh defines the source mesh
  85686. * @param name defines the name to use for the new target
  85687. * @param influence defines the influence to attach to the target
  85688. * @returns a new MorphTarget
  85689. */
  85690. MorphTarget.FromMesh = function (mesh, name, influence) {
  85691. if (!name) {
  85692. name = mesh.name;
  85693. }
  85694. var result = new MorphTarget(name, influence, mesh.getScene());
  85695. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85697. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85698. }
  85699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85700. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85701. }
  85702. return result;
  85703. };
  85704. return MorphTarget;
  85705. }());
  85706. BABYLON.MorphTarget = MorphTarget;
  85707. })(BABYLON || (BABYLON = {}));
  85708. //# sourceMappingURL=babylon.morphTarget.js.map
  85709. var BABYLON;
  85710. (function (BABYLON) {
  85711. /**
  85712. * This class is used to deform meshes using morphing between different targets
  85713. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85714. */
  85715. var MorphTargetManager = /** @class */ (function () {
  85716. /**
  85717. * Creates a new MorphTargetManager
  85718. * @param scene defines the current scene
  85719. */
  85720. function MorphTargetManager(scene) {
  85721. if (scene === void 0) { scene = null; }
  85722. this._targets = new Array();
  85723. this._targetObservable = new Array();
  85724. this._activeTargets = new BABYLON.SmartArray(16);
  85725. this._supportsNormals = false;
  85726. this._supportsTangents = false;
  85727. this._vertexCount = 0;
  85728. this._uniqueId = 0;
  85729. this._tempInfluences = new Array();
  85730. if (!scene) {
  85731. scene = BABYLON.Engine.LastCreatedScene;
  85732. }
  85733. this._scene = scene;
  85734. if (this._scene) {
  85735. this._scene.morphTargetManagers.push(this);
  85736. this._uniqueId = this._scene.getUniqueId();
  85737. }
  85738. }
  85739. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85740. /**
  85741. * Gets the unique ID of this manager
  85742. */
  85743. get: function () {
  85744. return this._uniqueId;
  85745. },
  85746. enumerable: true,
  85747. configurable: true
  85748. });
  85749. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85750. /**
  85751. * Gets the number of vertices handled by this manager
  85752. */
  85753. get: function () {
  85754. return this._vertexCount;
  85755. },
  85756. enumerable: true,
  85757. configurable: true
  85758. });
  85759. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85760. /**
  85761. * Gets a boolean indicating if this manager supports morphing of normals
  85762. */
  85763. get: function () {
  85764. return this._supportsNormals;
  85765. },
  85766. enumerable: true,
  85767. configurable: true
  85768. });
  85769. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85770. /**
  85771. * Gets a boolean indicating if this manager supports morphing of tangents
  85772. */
  85773. get: function () {
  85774. return this._supportsTangents;
  85775. },
  85776. enumerable: true,
  85777. configurable: true
  85778. });
  85779. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85780. /**
  85781. * Gets the number of targets stored in this manager
  85782. */
  85783. get: function () {
  85784. return this._targets.length;
  85785. },
  85786. enumerable: true,
  85787. configurable: true
  85788. });
  85789. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85790. /**
  85791. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85792. */
  85793. get: function () {
  85794. return this._activeTargets.length;
  85795. },
  85796. enumerable: true,
  85797. configurable: true
  85798. });
  85799. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85800. /**
  85801. * Gets the list of influences (one per target)
  85802. */
  85803. get: function () {
  85804. return this._influences;
  85805. },
  85806. enumerable: true,
  85807. configurable: true
  85808. });
  85809. /**
  85810. * Gets the active target at specified index. An active target is a target with an influence > 0
  85811. * @param index defines the index to check
  85812. * @returns the requested target
  85813. */
  85814. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85815. return this._activeTargets.data[index];
  85816. };
  85817. /**
  85818. * Gets the target at specified index
  85819. * @param index defines the index to check
  85820. * @returns the requested target
  85821. */
  85822. MorphTargetManager.prototype.getTarget = function (index) {
  85823. return this._targets[index];
  85824. };
  85825. /**
  85826. * Add a new target to this manager
  85827. * @param target defines the target to add
  85828. */
  85829. MorphTargetManager.prototype.addTarget = function (target) {
  85830. var _this = this;
  85831. this._targets.push(target);
  85832. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85833. _this._syncActiveTargets(needUpdate);
  85834. }));
  85835. this._syncActiveTargets(true);
  85836. };
  85837. /**
  85838. * Removes a target from the manager
  85839. * @param target defines the target to remove
  85840. */
  85841. MorphTargetManager.prototype.removeTarget = function (target) {
  85842. var index = this._targets.indexOf(target);
  85843. if (index >= 0) {
  85844. this._targets.splice(index, 1);
  85845. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85846. this._syncActiveTargets(true);
  85847. }
  85848. };
  85849. /**
  85850. * Serializes the current manager into a Serialization object
  85851. * @returns the serialized object
  85852. */
  85853. MorphTargetManager.prototype.serialize = function () {
  85854. var serializationObject = {};
  85855. serializationObject.id = this.uniqueId;
  85856. serializationObject.targets = [];
  85857. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85858. var target = _a[_i];
  85859. serializationObject.targets.push(target.serialize());
  85860. }
  85861. return serializationObject;
  85862. };
  85863. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85864. var influenceCount = 0;
  85865. this._activeTargets.reset();
  85866. this._supportsNormals = true;
  85867. this._supportsTangents = true;
  85868. this._vertexCount = 0;
  85869. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85870. var target = _a[_i];
  85871. this._activeTargets.push(target);
  85872. this._tempInfluences[influenceCount++] = target.influence;
  85873. var positions = target.getPositions();
  85874. if (positions) {
  85875. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85876. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85877. var vertexCount = positions.length / 3;
  85878. if (this._vertexCount === 0) {
  85879. this._vertexCount = vertexCount;
  85880. }
  85881. else if (this._vertexCount !== vertexCount) {
  85882. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85883. return;
  85884. }
  85885. }
  85886. }
  85887. if (!this._influences || this._influences.length !== influenceCount) {
  85888. this._influences = new Float32Array(influenceCount);
  85889. }
  85890. for (var index = 0; index < influenceCount; index++) {
  85891. this._influences[index] = this._tempInfluences[index];
  85892. }
  85893. if (needUpdate) {
  85894. this.synchronize();
  85895. }
  85896. };
  85897. /**
  85898. * Syncrhonize the targets with all the meshes using this morph target manager
  85899. */
  85900. MorphTargetManager.prototype.synchronize = function () {
  85901. if (!this._scene) {
  85902. return;
  85903. }
  85904. // Flag meshes as dirty to resync with the active targets
  85905. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85906. var mesh = _a[_i];
  85907. if (mesh.morphTargetManager === this) {
  85908. mesh._syncGeometryWithMorphTargetManager();
  85909. }
  85910. }
  85911. };
  85912. // Statics
  85913. /**
  85914. * Creates a new MorphTargetManager from serialized data
  85915. * @param serializationObject defines the serialized data
  85916. * @param scene defines the hosting scene
  85917. * @returns the new MorphTargetManager
  85918. */
  85919. MorphTargetManager.Parse = function (serializationObject, scene) {
  85920. var result = new MorphTargetManager(scene);
  85921. result._uniqueId = serializationObject.id;
  85922. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85923. var targetData = _a[_i];
  85924. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85925. }
  85926. return result;
  85927. };
  85928. return MorphTargetManager;
  85929. }());
  85930. BABYLON.MorphTargetManager = MorphTargetManager;
  85931. })(BABYLON || (BABYLON = {}));
  85932. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85933. var BABYLON;
  85934. (function (BABYLON) {
  85935. var Octree = /** @class */ (function () {
  85936. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85937. if (maxDepth === void 0) { maxDepth = 2; }
  85938. this.maxDepth = maxDepth;
  85939. this.dynamicContent = new Array();
  85940. this._maxBlockCapacity = maxBlockCapacity || 64;
  85941. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85942. this._creationFunc = creationFunc;
  85943. }
  85944. // Methods
  85945. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85946. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85947. };
  85948. Octree.prototype.addMesh = function (entry) {
  85949. for (var index = 0; index < this.blocks.length; index++) {
  85950. var block = this.blocks[index];
  85951. block.addEntry(entry);
  85952. }
  85953. };
  85954. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85955. this._selectionContent.reset();
  85956. for (var index = 0; index < this.blocks.length; index++) {
  85957. var block = this.blocks[index];
  85958. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85959. }
  85960. if (allowDuplicate) {
  85961. this._selectionContent.concat(this.dynamicContent);
  85962. }
  85963. else {
  85964. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85965. }
  85966. return this._selectionContent;
  85967. };
  85968. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85969. this._selectionContent.reset();
  85970. for (var index = 0; index < this.blocks.length; index++) {
  85971. var block = this.blocks[index];
  85972. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85973. }
  85974. if (allowDuplicate) {
  85975. this._selectionContent.concat(this.dynamicContent);
  85976. }
  85977. else {
  85978. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85979. }
  85980. return this._selectionContent;
  85981. };
  85982. Octree.prototype.intersectsRay = function (ray) {
  85983. this._selectionContent.reset();
  85984. for (var index = 0; index < this.blocks.length; index++) {
  85985. var block = this.blocks[index];
  85986. block.intersectsRay(ray, this._selectionContent);
  85987. }
  85988. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85989. return this._selectionContent;
  85990. };
  85991. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85992. target.blocks = new Array();
  85993. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85994. // Segmenting space
  85995. for (var x = 0; x < 2; x++) {
  85996. for (var y = 0; y < 2; y++) {
  85997. for (var z = 0; z < 2; z++) {
  85998. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85999. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86000. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86001. block.addEntries(entries);
  86002. target.blocks.push(block);
  86003. }
  86004. }
  86005. }
  86006. };
  86007. Octree.CreationFuncForMeshes = function (entry, block) {
  86008. var boundingInfo = entry.getBoundingInfo();
  86009. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86010. block.entries.push(entry);
  86011. }
  86012. };
  86013. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86014. var boundingInfo = entry.getBoundingInfo();
  86015. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86016. block.entries.push(entry);
  86017. }
  86018. };
  86019. return Octree;
  86020. }());
  86021. BABYLON.Octree = Octree;
  86022. })(BABYLON || (BABYLON = {}));
  86023. //# sourceMappingURL=babylon.octree.js.map
  86024. var BABYLON;
  86025. (function (BABYLON) {
  86026. var OctreeBlock = /** @class */ (function () {
  86027. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86028. this.entries = new Array();
  86029. this._boundingVectors = new Array();
  86030. this._capacity = capacity;
  86031. this._depth = depth;
  86032. this._maxDepth = maxDepth;
  86033. this._creationFunc = creationFunc;
  86034. this._minPoint = minPoint;
  86035. this._maxPoint = maxPoint;
  86036. this._boundingVectors.push(minPoint.clone());
  86037. this._boundingVectors.push(maxPoint.clone());
  86038. this._boundingVectors.push(minPoint.clone());
  86039. this._boundingVectors[2].x = maxPoint.x;
  86040. this._boundingVectors.push(minPoint.clone());
  86041. this._boundingVectors[3].y = maxPoint.y;
  86042. this._boundingVectors.push(minPoint.clone());
  86043. this._boundingVectors[4].z = maxPoint.z;
  86044. this._boundingVectors.push(maxPoint.clone());
  86045. this._boundingVectors[5].z = minPoint.z;
  86046. this._boundingVectors.push(maxPoint.clone());
  86047. this._boundingVectors[6].x = minPoint.x;
  86048. this._boundingVectors.push(maxPoint.clone());
  86049. this._boundingVectors[7].y = minPoint.y;
  86050. }
  86051. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86052. // Property
  86053. get: function () {
  86054. return this._capacity;
  86055. },
  86056. enumerable: true,
  86057. configurable: true
  86058. });
  86059. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86060. get: function () {
  86061. return this._minPoint;
  86062. },
  86063. enumerable: true,
  86064. configurable: true
  86065. });
  86066. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86067. get: function () {
  86068. return this._maxPoint;
  86069. },
  86070. enumerable: true,
  86071. configurable: true
  86072. });
  86073. // Methods
  86074. OctreeBlock.prototype.addEntry = function (entry) {
  86075. if (this.blocks) {
  86076. for (var index = 0; index < this.blocks.length; index++) {
  86077. var block = this.blocks[index];
  86078. block.addEntry(entry);
  86079. }
  86080. return;
  86081. }
  86082. this._creationFunc(entry, this);
  86083. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86084. this.createInnerBlocks();
  86085. }
  86086. };
  86087. OctreeBlock.prototype.addEntries = function (entries) {
  86088. for (var index = 0; index < entries.length; index++) {
  86089. var mesh = entries[index];
  86090. this.addEntry(mesh);
  86091. }
  86092. };
  86093. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86094. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86095. if (this.blocks) {
  86096. for (var index = 0; index < this.blocks.length; index++) {
  86097. var block = this.blocks[index];
  86098. block.select(frustumPlanes, selection, allowDuplicate);
  86099. }
  86100. return;
  86101. }
  86102. if (allowDuplicate) {
  86103. selection.concat(this.entries);
  86104. }
  86105. else {
  86106. selection.concatWithNoDuplicate(this.entries);
  86107. }
  86108. }
  86109. };
  86110. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86111. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86112. if (this.blocks) {
  86113. for (var index = 0; index < this.blocks.length; index++) {
  86114. var block = this.blocks[index];
  86115. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86116. }
  86117. return;
  86118. }
  86119. if (allowDuplicate) {
  86120. selection.concat(this.entries);
  86121. }
  86122. else {
  86123. selection.concatWithNoDuplicate(this.entries);
  86124. }
  86125. }
  86126. };
  86127. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86128. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86129. if (this.blocks) {
  86130. for (var index = 0; index < this.blocks.length; index++) {
  86131. var block = this.blocks[index];
  86132. block.intersectsRay(ray, selection);
  86133. }
  86134. return;
  86135. }
  86136. selection.concatWithNoDuplicate(this.entries);
  86137. }
  86138. };
  86139. OctreeBlock.prototype.createInnerBlocks = function () {
  86140. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86141. };
  86142. return OctreeBlock;
  86143. }());
  86144. BABYLON.OctreeBlock = OctreeBlock;
  86145. })(BABYLON || (BABYLON = {}));
  86146. //# sourceMappingURL=babylon.octreeBlock.js.map
  86147. var BABYLON;
  86148. (function (BABYLON) {
  86149. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86150. __extends(VRDistortionCorrectionPostProcess, _super);
  86151. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86152. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86153. 'LensCenter',
  86154. 'Scale',
  86155. 'ScaleIn',
  86156. 'HmdWarpParam'
  86157. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86158. _this._isRightEye = isRightEye;
  86159. _this._distortionFactors = vrMetrics.distortionK;
  86160. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86161. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86162. _this.adaptScaleToCurrentViewport = true;
  86163. _this.onSizeChangedObservable.add(function () {
  86164. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86165. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86166. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86167. });
  86168. _this.onApplyObservable.add(function (effect) {
  86169. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86170. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86171. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86172. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86173. });
  86174. return _this;
  86175. }
  86176. return VRDistortionCorrectionPostProcess;
  86177. }(BABYLON.PostProcess));
  86178. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86179. })(BABYLON || (BABYLON = {}));
  86180. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86181. var BABYLON;
  86182. (function (BABYLON) {
  86183. /**
  86184. * Postprocess used to generate anaglyphic rendering
  86185. */
  86186. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86187. __extends(AnaglyphPostProcess, _super);
  86188. /**
  86189. * Creates a new AnaglyphPostProcess
  86190. * @param name defines postprocess name
  86191. * @param options defines creation options or target ratio scale
  86192. * @param rigCameras defines cameras using this postprocess
  86193. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86194. * @param engine defines hosting engine
  86195. * @param reusable defines if the postprocess will be reused multiple times per frame
  86196. */
  86197. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86198. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86199. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86200. _this.onApplyObservable.add(function (effect) {
  86201. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86202. });
  86203. return _this;
  86204. }
  86205. return AnaglyphPostProcess;
  86206. }(BABYLON.PostProcess));
  86207. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86208. })(BABYLON || (BABYLON = {}));
  86209. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86210. var BABYLON;
  86211. (function (BABYLON) {
  86212. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86213. __extends(StereoscopicInterlacePostProcess, _super);
  86214. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86215. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86216. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86217. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86218. _this.onSizeChangedObservable.add(function () {
  86219. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86220. });
  86221. _this.onApplyObservable.add(function (effect) {
  86222. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86223. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86224. });
  86225. return _this;
  86226. }
  86227. return StereoscopicInterlacePostProcess;
  86228. }(BABYLON.PostProcess));
  86229. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86230. })(BABYLON || (BABYLON = {}));
  86231. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86232. var BABYLON;
  86233. (function (BABYLON) {
  86234. /**
  86235. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86236. * Screen rotation is taken into account.
  86237. */
  86238. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86239. function FreeCameraDeviceOrientationInput() {
  86240. var _this = this;
  86241. this._screenOrientationAngle = 0;
  86242. this._screenQuaternion = new BABYLON.Quaternion();
  86243. this._alpha = 0;
  86244. this._beta = 0;
  86245. this._gamma = 0;
  86246. this._orientationChanged = function () {
  86247. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86248. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86249. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86250. };
  86251. this._deviceOrientation = function (evt) {
  86252. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86253. _this._beta = evt.beta !== null ? evt.beta : 0;
  86254. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86255. };
  86256. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86257. this._orientationChanged();
  86258. }
  86259. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86260. get: function () {
  86261. return this._camera;
  86262. },
  86263. set: function (camera) {
  86264. this._camera = camera;
  86265. if (this._camera != null && !this._camera.rotationQuaternion) {
  86266. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86267. }
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86273. window.addEventListener("orientationchange", this._orientationChanged);
  86274. window.addEventListener("deviceorientation", this._deviceOrientation);
  86275. //In certain cases, the attach control is called AFTER orientation was changed,
  86276. //So this is needed.
  86277. this._orientationChanged();
  86278. };
  86279. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86280. window.removeEventListener("orientationchange", this._orientationChanged);
  86281. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86282. };
  86283. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86284. //if no device orientation provided, don't update the rotation.
  86285. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86286. if (!this._alpha)
  86287. return;
  86288. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86289. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86290. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86291. //Mirror on XY Plane
  86292. this._camera.rotationQuaternion.z *= -1;
  86293. this._camera.rotationQuaternion.w *= -1;
  86294. };
  86295. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86296. return "FreeCameraDeviceOrientationInput";
  86297. };
  86298. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86299. return "deviceOrientation";
  86300. };
  86301. return FreeCameraDeviceOrientationInput;
  86302. }());
  86303. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86304. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86305. })(BABYLON || (BABYLON = {}));
  86306. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86307. var BABYLON;
  86308. (function (BABYLON) {
  86309. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86310. function ArcRotateCameraVRDeviceOrientationInput() {
  86311. this.alphaCorrection = 1;
  86312. this.betaCorrection = 1;
  86313. this.gammaCorrection = 1;
  86314. this._alpha = 0;
  86315. this._gamma = 0;
  86316. this._dirty = false;
  86317. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86318. }
  86319. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86320. this.camera.attachControl(element, noPreventDefault);
  86321. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86322. };
  86323. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86324. if (evt.alpha !== null) {
  86325. this._alpha = +evt.alpha | 0;
  86326. }
  86327. if (evt.gamma !== null) {
  86328. this._gamma = +evt.gamma | 0;
  86329. }
  86330. this._dirty = true;
  86331. };
  86332. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86333. if (this._dirty) {
  86334. this._dirty = false;
  86335. if (this._gamma < 0) {
  86336. this._gamma = 180 + this._gamma;
  86337. }
  86338. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86339. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86340. }
  86341. };
  86342. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86343. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86344. };
  86345. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86346. return "ArcRotateCameraVRDeviceOrientationInput";
  86347. };
  86348. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86349. return "VRDeviceOrientation";
  86350. };
  86351. return ArcRotateCameraVRDeviceOrientationInput;
  86352. }());
  86353. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86354. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86355. })(BABYLON || (BABYLON = {}));
  86356. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86357. var BABYLON;
  86358. (function (BABYLON) {
  86359. var VRCameraMetrics = /** @class */ (function () {
  86360. function VRCameraMetrics() {
  86361. this.compensateDistortion = true;
  86362. }
  86363. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86364. get: function () {
  86365. return this.hResolution / (2 * this.vResolution);
  86366. },
  86367. enumerable: true,
  86368. configurable: true
  86369. });
  86370. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86371. get: function () {
  86372. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86373. },
  86374. enumerable: true,
  86375. configurable: true
  86376. });
  86377. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86378. get: function () {
  86379. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86380. var h = (4 * meters) / this.hScreenSize;
  86381. return BABYLON.Matrix.Translation(h, 0, 0);
  86382. },
  86383. enumerable: true,
  86384. configurable: true
  86385. });
  86386. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86387. get: function () {
  86388. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86389. var h = (4 * meters) / this.hScreenSize;
  86390. return BABYLON.Matrix.Translation(-h, 0, 0);
  86391. },
  86392. enumerable: true,
  86393. configurable: true
  86394. });
  86395. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86396. get: function () {
  86397. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86398. },
  86399. enumerable: true,
  86400. configurable: true
  86401. });
  86402. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86403. get: function () {
  86404. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86405. },
  86406. enumerable: true,
  86407. configurable: true
  86408. });
  86409. VRCameraMetrics.GetDefault = function () {
  86410. var result = new VRCameraMetrics();
  86411. result.hResolution = 1280;
  86412. result.vResolution = 800;
  86413. result.hScreenSize = 0.149759993;
  86414. result.vScreenSize = 0.0935999975;
  86415. result.vScreenCenter = 0.0467999987;
  86416. result.eyeToScreenDistance = 0.0410000011;
  86417. result.lensSeparationDistance = 0.0635000020;
  86418. result.interpupillaryDistance = 0.0640000030;
  86419. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86420. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86421. result.postProcessScaleFactor = 1.714605507808412;
  86422. result.lensCenterOffset = 0.151976421;
  86423. return result;
  86424. };
  86425. return VRCameraMetrics;
  86426. }());
  86427. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86428. })(BABYLON || (BABYLON = {}));
  86429. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86430. var BABYLON;
  86431. (function (BABYLON) {
  86432. /**
  86433. * This represents a WebVR camera.
  86434. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86435. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86436. */
  86437. var WebVRFreeCamera = /** @class */ (function (_super) {
  86438. __extends(WebVRFreeCamera, _super);
  86439. /**
  86440. * Instantiates a WebVRFreeCamera.
  86441. * @param name The name of the WebVRFreeCamera
  86442. * @param position The starting anchor position for the camera
  86443. * @param scene The scene the camera belongs to
  86444. * @param webVROptions a set of customizable options for the webVRCamera
  86445. */
  86446. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86447. if (webVROptions === void 0) { webVROptions = {}; }
  86448. var _this = _super.call(this, name, position, scene) || this;
  86449. _this.webVROptions = webVROptions;
  86450. /**
  86451. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86452. */
  86453. _this._vrDevice = null;
  86454. /**
  86455. * The rawPose of the vrDevice.
  86456. */
  86457. _this.rawPose = null;
  86458. _this._specsVersion = "1.1";
  86459. _this._attached = false;
  86460. _this._descendants = [];
  86461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86463. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86464. _this._standingMatrix = null;
  86465. /**
  86466. * Represents device position in babylon space.
  86467. */
  86468. _this.devicePosition = BABYLON.Vector3.Zero();
  86469. /**
  86470. * Represents device rotation in babylon space.
  86471. */
  86472. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86473. /**
  86474. * The scale of the device to be used when translating from device space to babylon space.
  86475. */
  86476. _this.deviceScaleFactor = 1;
  86477. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86478. _this._worldToDevice = BABYLON.Matrix.Identity();
  86479. /**
  86480. * References to the webVR controllers for the vrDevice.
  86481. */
  86482. _this.controllers = [];
  86483. /**
  86484. * Emits an event when a controller is attached.
  86485. */
  86486. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86487. /**
  86488. * Emits an event when a controller's mesh has been loaded;
  86489. */
  86490. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86491. /**
  86492. * If the rig cameras be used as parent instead of this camera.
  86493. */
  86494. _this.rigParenting = true;
  86495. _this._defaultHeight = undefined;
  86496. _this._workingVector = BABYLON.Vector3.Zero();
  86497. _this._oneVector = BABYLON.Vector3.One();
  86498. _this._workingMatrix = BABYLON.Matrix.Identity();
  86499. _this._cache.position = BABYLON.Vector3.Zero();
  86500. if (webVROptions.defaultHeight) {
  86501. _this._defaultHeight = webVROptions.defaultHeight;
  86502. _this.position.y = _this._defaultHeight;
  86503. }
  86504. _this.minZ = 0.1;
  86505. //legacy support - the compensation boolean was removed.
  86506. if (arguments.length === 5) {
  86507. _this.webVROptions = arguments[4];
  86508. }
  86509. // default webVR options
  86510. if (_this.webVROptions.trackPosition == undefined) {
  86511. _this.webVROptions.trackPosition = true;
  86512. }
  86513. if (_this.webVROptions.controllerMeshes == undefined) {
  86514. _this.webVROptions.controllerMeshes = true;
  86515. }
  86516. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86517. _this.webVROptions.defaultLightingOnControllers = true;
  86518. }
  86519. _this.rotationQuaternion = new BABYLON.Quaternion();
  86520. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86521. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86522. }
  86523. //enable VR
  86524. var engine = _this.getEngine();
  86525. _this._onVREnabled = function (success) { if (success) {
  86526. _this.initControllers();
  86527. } };
  86528. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86529. engine.initWebVR().add(function (event) {
  86530. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86531. return;
  86532. }
  86533. _this._vrDevice = event.vrDisplay;
  86534. //reset the rig parameters.
  86535. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86536. if (_this._attached) {
  86537. _this.getEngine().enableVR();
  86538. }
  86539. });
  86540. if (typeof (VRFrameData) !== "undefined")
  86541. _this._frameData = new VRFrameData();
  86542. /**
  86543. * The idea behind the following lines:
  86544. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86545. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86546. * the second will not show it correctly.
  86547. *
  86548. * To solve this - each object that has the camera as parent will be added to a protected array.
  86549. * When the rig camera renders, it will take this array and set all of those to be its children.
  86550. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86551. * Amazing!
  86552. */
  86553. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86554. if (camera.parent === _this && _this.rigParenting) {
  86555. _this._descendants = _this.getDescendants(true, function (n) {
  86556. // don't take the cameras or the controllers!
  86557. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86558. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86559. return !isController && !isRigCamera;
  86560. });
  86561. _this._descendants.forEach(function (node) {
  86562. node.parent = camera;
  86563. });
  86564. }
  86565. });
  86566. scene.onAfterCameraRenderObservable.add(function (camera) {
  86567. if (camera.parent === _this && _this.rigParenting) {
  86568. _this._descendants.forEach(function (node) {
  86569. node.parent = _this;
  86570. });
  86571. }
  86572. });
  86573. return _this;
  86574. }
  86575. /**
  86576. * Gets the device distance from the ground in meters.
  86577. * @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.
  86578. */
  86579. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86580. if (this._standingMatrix) {
  86581. // Add standing matrix offset to get real offset from ground in room
  86582. this._standingMatrix.getTranslationToRef(this._workingVector);
  86583. return this._deviceRoomPosition.y + this._workingVector.y;
  86584. }
  86585. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86586. return this._defaultHeight || 0;
  86587. };
  86588. /**
  86589. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86590. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86591. */
  86592. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86593. var _this = this;
  86594. if (callback === void 0) { callback = function (bool) { }; }
  86595. // Use standing matrix if available
  86596. this.getEngine().initWebVRAsync().then(function (result) {
  86597. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86598. callback(false);
  86599. }
  86600. else {
  86601. _this._standingMatrix = new BABYLON.Matrix();
  86602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86603. if (!_this.getScene().useRightHandedSystem) {
  86604. [2, 6, 8, 9, 14].forEach(function (num) {
  86605. if (_this._standingMatrix) {
  86606. _this._standingMatrix.m[num] *= -1;
  86607. }
  86608. });
  86609. }
  86610. callback(true);
  86611. }
  86612. });
  86613. };
  86614. /**
  86615. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86616. * @returns A promise with a boolean set to if the standing matrix is supported.
  86617. */
  86618. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86619. var _this = this;
  86620. return new Promise(function (res, rej) {
  86621. _this.useStandingMatrix(function (supported) {
  86622. res(supported);
  86623. });
  86624. });
  86625. };
  86626. /**
  86627. * Disposes the camera
  86628. */
  86629. WebVRFreeCamera.prototype.dispose = function () {
  86630. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86631. _super.prototype.dispose.call(this);
  86632. };
  86633. /**
  86634. * Gets a vrController by name.
  86635. * @param name The name of the controller to retreive
  86636. * @returns the controller matching the name specified or null if not found
  86637. */
  86638. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86639. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86640. var gp = _a[_i];
  86641. if (gp.hand === name) {
  86642. return gp;
  86643. }
  86644. }
  86645. return null;
  86646. };
  86647. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86648. /**
  86649. * The controller corrisponding to the users left hand.
  86650. */
  86651. get: function () {
  86652. if (!this._leftController) {
  86653. this._leftController = this.getControllerByName("left");
  86654. }
  86655. return this._leftController;
  86656. },
  86657. enumerable: true,
  86658. configurable: true
  86659. });
  86660. ;
  86661. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86662. /**
  86663. * The controller corrisponding to the users right hand.
  86664. */
  86665. get: function () {
  86666. if (!this._rightController) {
  86667. this._rightController = this.getControllerByName("right");
  86668. }
  86669. return this._rightController;
  86670. },
  86671. enumerable: true,
  86672. configurable: true
  86673. });
  86674. ;
  86675. /**
  86676. * Casts a ray forward from the vrCamera's gaze.
  86677. * @param length Length of the ray (default: 100)
  86678. * @returns the ray corrisponding to the gaze
  86679. */
  86680. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86681. if (length === void 0) { length = 100; }
  86682. if (this.leftCamera) {
  86683. // Use left eye to avoid computation to compute center on every call
  86684. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86685. }
  86686. else {
  86687. return _super.prototype.getForwardRay.call(this, length);
  86688. }
  86689. };
  86690. /**
  86691. * Updates the camera based on device's frame data
  86692. */
  86693. WebVRFreeCamera.prototype._checkInputs = function () {
  86694. if (this._vrDevice && this._vrDevice.isPresenting) {
  86695. this._vrDevice.getFrameData(this._frameData);
  86696. this.updateFromDevice(this._frameData.pose);
  86697. }
  86698. _super.prototype._checkInputs.call(this);
  86699. };
  86700. /**
  86701. * Updates the poseControlled values based on the input device pose.
  86702. * @param poseData Pose coming from the device
  86703. */
  86704. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86705. if (poseData && poseData.orientation) {
  86706. this.rawPose = poseData;
  86707. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86708. if (this.getScene().useRightHandedSystem) {
  86709. this._deviceRoomRotationQuaternion.z *= -1;
  86710. this._deviceRoomRotationQuaternion.w *= -1;
  86711. }
  86712. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86713. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86714. if (this.getScene().useRightHandedSystem) {
  86715. this._deviceRoomPosition.z *= -1;
  86716. }
  86717. }
  86718. }
  86719. };
  86720. /**
  86721. * WebVR's attach control will start broadcasting frames to the device.
  86722. * Note that in certain browsers (chrome for example) this function must be called
  86723. * within a user-interaction callback. Example:
  86724. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86725. *
  86726. * @param element html element to attach the vrDevice to
  86727. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86728. */
  86729. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86730. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86731. this._attached = true;
  86732. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86733. if (this._vrDevice) {
  86734. this.getEngine().enableVR();
  86735. }
  86736. };
  86737. /**
  86738. * Detaches the camera from the html element and disables VR
  86739. *
  86740. * @param element html element to detach from
  86741. */
  86742. WebVRFreeCamera.prototype.detachControl = function (element) {
  86743. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86744. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86745. _super.prototype.detachControl.call(this, element);
  86746. this._attached = false;
  86747. this.getEngine().disableVR();
  86748. };
  86749. /**
  86750. * @returns the name of this class
  86751. */
  86752. WebVRFreeCamera.prototype.getClassName = function () {
  86753. return "WebVRFreeCamera";
  86754. };
  86755. /**
  86756. * Calls resetPose on the vrDisplay
  86757. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86758. */
  86759. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86760. //uses the vrDisplay's "resetPose()".
  86761. //pitch and roll won't be affected.
  86762. this._vrDevice.resetPose();
  86763. };
  86764. /**
  86765. * Updates the rig cameras (left and right eye)
  86766. */
  86767. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86768. var camLeft = this._rigCameras[0];
  86769. var camRight = this._rigCameras[1];
  86770. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86771. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86772. camLeft.position.copyFrom(this._deviceRoomPosition);
  86773. camRight.position.copyFrom(this._deviceRoomPosition);
  86774. };
  86775. /**
  86776. * Updates the cached values of the camera
  86777. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86778. */
  86779. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86780. var _this = this;
  86781. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86782. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86783. if (!this.updateCacheCalled) {
  86784. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86785. this.updateCacheCalled = true;
  86786. this.update();
  86787. }
  86788. // Set working vector to the device position in room space rotated by the new rotation
  86789. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86790. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86791. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86792. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86793. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86794. // Add translation from anchor position
  86795. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86796. this._workingVector.addInPlace(this.position);
  86797. this._workingVector.subtractInPlace(this._cache.position);
  86798. this._deviceToWorld.setTranslation(this._workingVector);
  86799. // Set an inverted matrix to be used when updating the camera
  86800. this._deviceToWorld.invertToRef(this._worldToDevice);
  86801. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86802. this.controllers.forEach(function (controller) {
  86803. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86804. controller.update();
  86805. });
  86806. }
  86807. if (!ignoreParentClass) {
  86808. _super.prototype._updateCache.call(this);
  86809. }
  86810. this.updateCacheCalled = false;
  86811. };
  86812. /**
  86813. * Updates the current device position and rotation in the babylon world
  86814. */
  86815. WebVRFreeCamera.prototype.update = function () {
  86816. // Get current device position in babylon world
  86817. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86818. // Get current device rotation in babylon world
  86819. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86820. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86821. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86822. _super.prototype.update.call(this);
  86823. };
  86824. /**
  86825. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86826. * @returns an identity matrix
  86827. */
  86828. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86829. return BABYLON.Matrix.Identity();
  86830. };
  86831. /**
  86832. * This function is called by the two RIG cameras.
  86833. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86834. */
  86835. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86836. var _this = this;
  86837. // Update the parent camera prior to using a child camera to avoid desynchronization
  86838. var parentCamera = this._cameraRigParams["parentCamera"];
  86839. parentCamera._updateCache();
  86840. //WebVR 1.1
  86841. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86842. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86843. if (!this.getScene().useRightHandedSystem) {
  86844. [2, 6, 8, 9, 14].forEach(function (num) {
  86845. _this._webvrViewMatrix.m[num] *= -1;
  86846. });
  86847. }
  86848. // update the camera rotation matrix
  86849. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86850. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86851. // Computing target and final matrix
  86852. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86853. // should the view matrix be updated with scale and position offset?
  86854. if (parentCamera.deviceScaleFactor !== 1) {
  86855. this._webvrViewMatrix.invert();
  86856. // scale the position, if set
  86857. if (parentCamera.deviceScaleFactor) {
  86858. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86859. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86860. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86861. }
  86862. this._webvrViewMatrix.invert();
  86863. }
  86864. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86865. // Compute global position
  86866. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86867. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86868. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86869. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86870. this._markSyncedWithParent();
  86871. return this._webvrViewMatrix;
  86872. };
  86873. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86874. var _this = this;
  86875. var parentCamera = this.parent;
  86876. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86877. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86878. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86879. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86880. //babylon compatible matrix
  86881. if (!this.getScene().useRightHandedSystem) {
  86882. [8, 9, 10, 11].forEach(function (num) {
  86883. _this._projectionMatrix.m[num] *= -1;
  86884. });
  86885. }
  86886. return this._projectionMatrix;
  86887. };
  86888. /**
  86889. * Initializes the controllers and their meshes
  86890. */
  86891. WebVRFreeCamera.prototype.initControllers = function () {
  86892. var _this = this;
  86893. this.controllers = [];
  86894. var manager = this.getScene().gamepadManager;
  86895. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86896. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86897. var webVrController = gamepad;
  86898. if (webVrController.defaultModel) {
  86899. webVrController.defaultModel.setEnabled(false);
  86900. }
  86901. if (webVrController.hand === "right") {
  86902. _this._rightController = null;
  86903. }
  86904. if (webVrController.hand === "left") {
  86905. _this._leftController = null;
  86906. }
  86907. var controllerIndex = _this.controllers.indexOf(webVrController);
  86908. if (controllerIndex !== -1) {
  86909. _this.controllers.splice(controllerIndex, 1);
  86910. }
  86911. }
  86912. });
  86913. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86914. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86915. var webVrController_1 = gamepad;
  86916. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86917. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86918. if (_this.webVROptions.controllerMeshes) {
  86919. if (webVrController_1.defaultModel) {
  86920. webVrController_1.defaultModel.setEnabled(true);
  86921. }
  86922. else {
  86923. // Load the meshes
  86924. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86925. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86926. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86927. if (_this.webVROptions.defaultLightingOnControllers) {
  86928. if (!_this._lightOnControllers) {
  86929. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86930. }
  86931. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86932. var children = mesh.getChildren();
  86933. if (children.length !== 0) {
  86934. children.forEach(function (mesh) {
  86935. light.includedOnlyMeshes.push(mesh);
  86936. activateLightOnSubMeshes_1(mesh, light);
  86937. });
  86938. }
  86939. };
  86940. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86941. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86942. }
  86943. });
  86944. }
  86945. }
  86946. webVrController_1.attachToPoseControlledCamera(_this);
  86947. // since this is async - sanity check. Is the controller already stored?
  86948. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86949. //add to the controllers array
  86950. _this.controllers.push(webVrController_1);
  86951. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86952. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86953. // So we're overriding setting left & right manually to be sure
  86954. var firstViveWandDetected = false;
  86955. for (var i = 0; i < _this.controllers.length; i++) {
  86956. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86957. if (!firstViveWandDetected) {
  86958. firstViveWandDetected = true;
  86959. _this.controllers[i].hand = "left";
  86960. }
  86961. else {
  86962. _this.controllers[i].hand = "right";
  86963. }
  86964. }
  86965. }
  86966. //did we find enough controllers? Great! let the developer know.
  86967. if (_this.controllers.length >= 2) {
  86968. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86969. }
  86970. }
  86971. }
  86972. });
  86973. };
  86974. return WebVRFreeCamera;
  86975. }(BABYLON.FreeCamera));
  86976. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86977. })(BABYLON || (BABYLON = {}));
  86978. //# sourceMappingURL=babylon.webVRCamera.js.map
  86979. var BABYLON;
  86980. (function (BABYLON) {
  86981. // We're mainly based on the logic defined into the FreeCamera code
  86982. /**
  86983. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86984. * being tilted forward or back and left or right.
  86985. */
  86986. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86987. __extends(DeviceOrientationCamera, _super);
  86988. /**
  86989. * Creates a new device orientation camera
  86990. * @param name The name of the camera
  86991. * @param position The start position camera
  86992. * @param scene The scene the camera belongs to
  86993. */
  86994. function DeviceOrientationCamera(name, position, scene) {
  86995. var _this = _super.call(this, name, position, scene) || this;
  86996. _this._quaternionCache = new BABYLON.Quaternion();
  86997. _this.inputs.addDeviceOrientation();
  86998. return _this;
  86999. }
  87000. /**
  87001. * Gets the current instance class name ("DeviceOrientationCamera").
  87002. * This helps avoiding instanceof at run time.
  87003. * @returns the class name
  87004. */
  87005. DeviceOrientationCamera.prototype.getClassName = function () {
  87006. return "DeviceOrientationCamera";
  87007. };
  87008. /**
  87009. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87010. */
  87011. DeviceOrientationCamera.prototype._checkInputs = function () {
  87012. _super.prototype._checkInputs.call(this);
  87013. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87014. if (this._initialQuaternion) {
  87015. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87016. }
  87017. };
  87018. /**
  87019. * Reset the camera to its default orientation on the specified axis only.
  87020. * @param axis The axis to reset
  87021. */
  87022. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87023. var _this = this;
  87024. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87025. //can only work if this camera has a rotation quaternion already.
  87026. if (!this.rotationQuaternion)
  87027. return;
  87028. if (!this._initialQuaternion) {
  87029. this._initialQuaternion = new BABYLON.Quaternion();
  87030. }
  87031. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87032. ['x', 'y', 'z'].forEach(function (axisName) {
  87033. if (!axis[axisName]) {
  87034. _this._initialQuaternion[axisName] = 0;
  87035. }
  87036. else {
  87037. _this._initialQuaternion[axisName] *= -1;
  87038. }
  87039. });
  87040. this._initialQuaternion.normalize();
  87041. //force rotation update
  87042. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87043. };
  87044. return DeviceOrientationCamera;
  87045. }(BABYLON.FreeCamera));
  87046. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87052. __extends(VRDeviceOrientationFreeCamera, _super);
  87053. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87054. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87055. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87056. var _this = _super.call(this, name, position, scene) || this;
  87057. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87058. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87059. return _this;
  87060. }
  87061. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87062. return "VRDeviceOrientationFreeCamera";
  87063. };
  87064. return VRDeviceOrientationFreeCamera;
  87065. }(BABYLON.DeviceOrientationCamera));
  87066. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87067. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87068. __extends(VRDeviceOrientationGamepadCamera, _super);
  87069. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87070. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87071. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87072. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87073. _this.inputs.addGamepad();
  87074. return _this;
  87075. }
  87076. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87077. return "VRDeviceOrientationGamepadCamera";
  87078. };
  87079. return VRDeviceOrientationGamepadCamera;
  87080. }(VRDeviceOrientationFreeCamera));
  87081. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87082. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87083. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87084. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87085. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87086. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87087. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87088. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87089. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87090. _this.inputs.addVRDeviceOrientation();
  87091. return _this;
  87092. }
  87093. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87094. return "VRDeviceOrientationArcRotateCamera";
  87095. };
  87096. return VRDeviceOrientationArcRotateCamera;
  87097. }(BABYLON.ArcRotateCamera));
  87098. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87099. })(BABYLON || (BABYLON = {}));
  87100. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87101. var BABYLON;
  87102. (function (BABYLON) {
  87103. /**
  87104. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87105. */
  87106. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87107. __extends(AnaglyphFreeCamera, _super);
  87108. /**
  87109. * Creates a new AnaglyphFreeCamera
  87110. * @param name defines camera name
  87111. * @param position defines initial position
  87112. * @param interaxialDistance defines distance between each color axis
  87113. * @param scene defines the hosting scene
  87114. */
  87115. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87116. var _this = _super.call(this, name, position, scene) || this;
  87117. _this.interaxialDistance = interaxialDistance;
  87118. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87119. return _this;
  87120. }
  87121. /**
  87122. * Gets camera class name
  87123. * @returns AnaglyphFreeCamera
  87124. */
  87125. AnaglyphFreeCamera.prototype.getClassName = function () {
  87126. return "AnaglyphFreeCamera";
  87127. };
  87128. return AnaglyphFreeCamera;
  87129. }(BABYLON.FreeCamera));
  87130. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87131. /**
  87132. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87133. */
  87134. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87135. __extends(AnaglyphArcRotateCamera, _super);
  87136. /**
  87137. * Creates a new AnaglyphArcRotateCamera
  87138. * @param name defines camera name
  87139. * @param alpha defines alpha angle (in radians)
  87140. * @param beta defines beta angle (in radians)
  87141. * @param radius defines radius
  87142. * @param target defines camera target
  87143. * @param interaxialDistance defines distance between each color axis
  87144. * @param scene defines the hosting scene
  87145. */
  87146. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87147. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87148. _this.interaxialDistance = interaxialDistance;
  87149. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87150. return _this;
  87151. }
  87152. /**
  87153. * Gets camera class name
  87154. * @returns AnaglyphArcRotateCamera
  87155. */
  87156. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87157. return "AnaglyphArcRotateCamera";
  87158. };
  87159. return AnaglyphArcRotateCamera;
  87160. }(BABYLON.ArcRotateCamera));
  87161. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87162. /**
  87163. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87164. */
  87165. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87166. __extends(AnaglyphGamepadCamera, _super);
  87167. /**
  87168. * Creates a new AnaglyphGamepadCamera
  87169. * @param name defines camera name
  87170. * @param position defines initial position
  87171. * @param interaxialDistance defines distance between each color axis
  87172. * @param scene defines the hosting scene
  87173. */
  87174. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87175. var _this = _super.call(this, name, position, scene) || this;
  87176. _this.interaxialDistance = interaxialDistance;
  87177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87178. return _this;
  87179. }
  87180. /**
  87181. * Gets camera class name
  87182. * @returns AnaglyphGamepadCamera
  87183. */
  87184. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87185. return "AnaglyphGamepadCamera";
  87186. };
  87187. return AnaglyphGamepadCamera;
  87188. }(BABYLON.GamepadCamera));
  87189. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87190. /**
  87191. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87192. */
  87193. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87194. __extends(AnaglyphUniversalCamera, _super);
  87195. /**
  87196. * Creates a new AnaglyphUniversalCamera
  87197. * @param name defines camera name
  87198. * @param position defines initial position
  87199. * @param interaxialDistance defines distance between each color axis
  87200. * @param scene defines the hosting scene
  87201. */
  87202. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87203. var _this = _super.call(this, name, position, scene) || this;
  87204. _this.interaxialDistance = interaxialDistance;
  87205. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87206. return _this;
  87207. }
  87208. /**
  87209. * Gets camera class name
  87210. * @returns AnaglyphUniversalCamera
  87211. */
  87212. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87213. return "AnaglyphUniversalCamera";
  87214. };
  87215. return AnaglyphUniversalCamera;
  87216. }(BABYLON.UniversalCamera));
  87217. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87218. /**
  87219. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87220. */
  87221. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87222. __extends(StereoscopicFreeCamera, _super);
  87223. /**
  87224. * Creates a new StereoscopicFreeCamera
  87225. * @param name defines camera name
  87226. * @param position defines initial position
  87227. * @param interaxialDistance defines distance between each color axis
  87228. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87229. * @param scene defines the hosting scene
  87230. */
  87231. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87232. var _this = _super.call(this, name, position, scene) || this;
  87233. _this.interaxialDistance = interaxialDistance;
  87234. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87235. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87236. return _this;
  87237. }
  87238. /**
  87239. * Gets camera class name
  87240. * @returns StereoscopicFreeCamera
  87241. */
  87242. StereoscopicFreeCamera.prototype.getClassName = function () {
  87243. return "StereoscopicFreeCamera";
  87244. };
  87245. return StereoscopicFreeCamera;
  87246. }(BABYLON.FreeCamera));
  87247. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87248. /**
  87249. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87250. */
  87251. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87252. __extends(StereoscopicArcRotateCamera, _super);
  87253. /**
  87254. * Creates a new StereoscopicArcRotateCamera
  87255. * @param name defines camera name
  87256. * @param alpha defines alpha angle (in radians)
  87257. * @param beta defines beta angle (in radians)
  87258. * @param radius defines radius
  87259. * @param target defines camera target
  87260. * @param interaxialDistance defines distance between each color axis
  87261. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87262. * @param scene defines the hosting scene
  87263. */
  87264. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87265. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87266. _this.interaxialDistance = interaxialDistance;
  87267. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87268. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87269. return _this;
  87270. }
  87271. /**
  87272. * Gets camera class name
  87273. * @returns StereoscopicArcRotateCamera
  87274. */
  87275. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87276. return "StereoscopicArcRotateCamera";
  87277. };
  87278. return StereoscopicArcRotateCamera;
  87279. }(BABYLON.ArcRotateCamera));
  87280. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87281. /**
  87282. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87283. */
  87284. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87285. __extends(StereoscopicGamepadCamera, _super);
  87286. /**
  87287. * Creates a new StereoscopicGamepadCamera
  87288. * @param name defines camera name
  87289. * @param position defines initial position
  87290. * @param interaxialDistance defines distance between each color axis
  87291. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87292. * @param scene defines the hosting scene
  87293. */
  87294. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87295. var _this = _super.call(this, name, position, scene) || this;
  87296. _this.interaxialDistance = interaxialDistance;
  87297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87299. return _this;
  87300. }
  87301. /**
  87302. * Gets camera class name
  87303. * @returns StereoscopicGamepadCamera
  87304. */
  87305. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87306. return "StereoscopicGamepadCamera";
  87307. };
  87308. return StereoscopicGamepadCamera;
  87309. }(BABYLON.GamepadCamera));
  87310. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87311. /**
  87312. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87313. */
  87314. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87315. __extends(StereoscopicUniversalCamera, _super);
  87316. /**
  87317. * Creates a new StereoscopicUniversalCamera
  87318. * @param name defines camera name
  87319. * @param position defines initial position
  87320. * @param interaxialDistance defines distance between each color axis
  87321. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87322. * @param scene defines the hosting scene
  87323. */
  87324. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87325. var _this = _super.call(this, name, position, scene) || this;
  87326. _this.interaxialDistance = interaxialDistance;
  87327. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87328. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87329. return _this;
  87330. }
  87331. /**
  87332. * Gets camera class name
  87333. * @returns StereoscopicUniversalCamera
  87334. */
  87335. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87336. return "StereoscopicUniversalCamera";
  87337. };
  87338. return StereoscopicUniversalCamera;
  87339. }(BABYLON.UniversalCamera));
  87340. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87341. })(BABYLON || (BABYLON = {}));
  87342. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87343. var BABYLON;
  87344. (function (BABYLON) {
  87345. var VRExperienceHelperGazer = /** @class */ (function () {
  87346. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87347. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87348. this.scene = scene;
  87349. this._pointerDownOnMeshAsked = false;
  87350. this._isActionableMesh = false;
  87351. this._teleportationRequestInitiated = false;
  87352. this._teleportationBackRequestInitiated = false;
  87353. this._rotationRightAsked = false;
  87354. this._rotationLeftAsked = false;
  87355. this._dpadPressed = true;
  87356. this._activePointer = false;
  87357. this._id = VRExperienceHelperGazer._idCounter++;
  87358. // Gaze tracker
  87359. if (!gazeTrackerToClone) {
  87360. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87361. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87362. this._gazeTracker.isPickable = false;
  87363. this._gazeTracker.isVisible = false;
  87364. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87365. targetMat.specularColor = BABYLON.Color3.Black();
  87366. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87367. targetMat.backFaceCulling = false;
  87368. this._gazeTracker.material = targetMat;
  87369. }
  87370. else {
  87371. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87372. }
  87373. }
  87374. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87375. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87376. };
  87377. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87378. this._pointerDownOnMeshAsked = true;
  87379. if (this._currentMeshSelected && this._currentHit) {
  87380. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87381. }
  87382. };
  87383. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87384. if (this._currentMeshSelected && this._currentHit) {
  87385. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87386. }
  87387. this._pointerDownOnMeshAsked = false;
  87388. };
  87389. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87390. this._activePointer = true;
  87391. };
  87392. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87393. this._activePointer = false;
  87394. };
  87395. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87396. if (distance === void 0) { distance = 100; }
  87397. };
  87398. VRExperienceHelperGazer.prototype.dispose = function () {
  87399. this._interactionsEnabled = false;
  87400. this._teleportationEnabled = false;
  87401. if (this._gazeTracker) {
  87402. this._gazeTracker.dispose();
  87403. }
  87404. };
  87405. VRExperienceHelperGazer._idCounter = 0;
  87406. return VRExperienceHelperGazer;
  87407. }());
  87408. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87409. __extends(VRExperienceHelperControllerGazer, _super);
  87410. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87411. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87412. _this.webVRController = webVRController;
  87413. // Laser pointer
  87414. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87415. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87416. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87417. laserPointerMaterial.alpha = 0.6;
  87418. _this._laserPointer.material = laserPointerMaterial;
  87419. _this._laserPointer.rotation.x = Math.PI / 2;
  87420. _this._laserPointer.position.z = -0.5;
  87421. _this._laserPointer.isVisible = false;
  87422. if (!webVRController.mesh) {
  87423. // Create an empty mesh that is used prior to loading the high quality model
  87424. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87425. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87426. preloadPointerPose.rotation.x = -0.7;
  87427. preloadMesh.addChild(preloadPointerPose);
  87428. webVRController.attachToMesh(preloadMesh);
  87429. }
  87430. _this._setLaserPointerParent(webVRController.mesh);
  87431. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87432. _this._setLaserPointerParent(mesh);
  87433. });
  87434. return _this;
  87435. }
  87436. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87437. return this.webVRController.getForwardRay(length);
  87438. };
  87439. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87440. _super.prototype._activatePointer.call(this);
  87441. this._laserPointer.isVisible = true;
  87442. };
  87443. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87444. _super.prototype._deactivatePointer.call(this);
  87445. this._laserPointer.isVisible = false;
  87446. };
  87447. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87448. this._laserPointer.material.emissiveColor = color;
  87449. };
  87450. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87451. var makeNotPick = function (root) {
  87452. root.name += " laserPointer";
  87453. root.getChildMeshes().forEach(function (c) {
  87454. makeNotPick(c);
  87455. });
  87456. };
  87457. makeNotPick(mesh);
  87458. var childMeshes = mesh.getChildMeshes();
  87459. this.webVRController._pointingPoseNode = null;
  87460. for (var i = 0; i < childMeshes.length; i++) {
  87461. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87462. mesh = childMeshes[i];
  87463. this.webVRController._pointingPoseNode = mesh;
  87464. break;
  87465. }
  87466. }
  87467. this._laserPointer.parent = mesh;
  87468. };
  87469. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87470. if (distance === void 0) { distance = 100; }
  87471. this._laserPointer.scaling.y = distance;
  87472. this._laserPointer.position.z = -distance / 2;
  87473. };
  87474. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87475. _super.prototype.dispose.call(this);
  87476. this._laserPointer.dispose();
  87477. if (this._meshAttachedObserver) {
  87478. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87479. }
  87480. };
  87481. return VRExperienceHelperControllerGazer;
  87482. }(VRExperienceHelperGazer));
  87483. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87484. __extends(VRExperienceHelperCameraGazer, _super);
  87485. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87486. var _this = _super.call(this, scene) || this;
  87487. _this.getCamera = getCamera;
  87488. return _this;
  87489. }
  87490. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87491. var camera = this.getCamera();
  87492. if (camera) {
  87493. return camera.getForwardRay(length);
  87494. }
  87495. else {
  87496. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87497. }
  87498. };
  87499. return VRExperienceHelperCameraGazer;
  87500. }(VRExperienceHelperGazer));
  87501. /**
  87502. * Helps to quickly add VR support to an existing scene.
  87503. * See http://doc.babylonjs.com/how_to/webvr_helper
  87504. */
  87505. var VRExperienceHelper = /** @class */ (function () {
  87506. /**
  87507. * Instantiates a VRExperienceHelper.
  87508. * Helps to quickly add VR support to an existing scene.
  87509. * @param scene The scene the VRExperienceHelper belongs to.
  87510. * @param webVROptions Options to modify the vr experience helper's behavior.
  87511. */
  87512. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87513. if (webVROptions === void 0) { webVROptions = {}; }
  87514. var _this = this;
  87515. this.webVROptions = webVROptions;
  87516. // Can the system support WebVR, even if a headset isn't plugged in?
  87517. this._webVRsupported = false;
  87518. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87519. this._webVRready = false;
  87520. // Are we waiting for the requestPresent callback to complete?
  87521. this._webVRrequesting = false;
  87522. // Are we presenting to the headset right now?
  87523. this._webVRpresenting = false;
  87524. // Are we presenting in the fullscreen fallback?
  87525. this._fullscreenVRpresenting = false;
  87526. /**
  87527. * Observable raised when entering VR.
  87528. */
  87529. this.onEnteringVRObservable = new BABYLON.Observable();
  87530. /**
  87531. * Observable raised when exiting VR.
  87532. */
  87533. this.onExitingVRObservable = new BABYLON.Observable();
  87534. /**
  87535. * Observable raised when controller mesh is loaded.
  87536. */
  87537. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87538. this._useCustomVRButton = false;
  87539. this._teleportationRequested = false;
  87540. this._teleportActive = false;
  87541. this._floorMeshesCollection = [];
  87542. this._rotationAllowed = true;
  87543. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87544. this._isDefaultTeleportationTarget = true;
  87545. this._teleportationFillColor = "#444444";
  87546. this._teleportationBorderColor = "#FFFFFF";
  87547. this._rotationAngle = 0;
  87548. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87549. this._padSensibilityUp = 0.65;
  87550. this._padSensibilityDown = 0.35;
  87551. this.leftController = null;
  87552. this.rightController = null;
  87553. /**
  87554. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87555. */
  87556. this.onNewMeshSelected = new BABYLON.Observable();
  87557. /**
  87558. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87559. */
  87560. this.onNewMeshPicked = new BABYLON.Observable();
  87561. /**
  87562. * Observable raised before camera teleportation
  87563. */
  87564. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87565. /**
  87566. * Observable raised after camera teleportation
  87567. */
  87568. this.onAfterCameraTeleport = new BABYLON.Observable();
  87569. /**
  87570. * Observable raised when current selected mesh gets unselected
  87571. */
  87572. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87573. /**
  87574. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87575. */
  87576. this.teleportationEnabled = true;
  87577. this._teleportationInitialized = false;
  87578. this._interactionsEnabled = false;
  87579. this._interactionsRequested = false;
  87580. this._displayGaze = true;
  87581. this._displayLaserPointer = true;
  87582. this._onResize = function () {
  87583. _this.moveButtonToBottomRight();
  87584. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87585. _this.exitVR();
  87586. }
  87587. };
  87588. this._onFullscreenChange = function () {
  87589. if (document.fullscreen !== undefined) {
  87590. _this._fullscreenVRpresenting = document.fullscreen;
  87591. }
  87592. else if (document.mozFullScreen !== undefined) {
  87593. _this._fullscreenVRpresenting = document.mozFullScreen;
  87594. }
  87595. else if (document.webkitIsFullScreen !== undefined) {
  87596. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87597. }
  87598. else if (document.msIsFullScreen !== undefined) {
  87599. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87600. }
  87601. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87602. _this.exitVR();
  87603. if (!_this._useCustomVRButton) {
  87604. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87605. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87606. }
  87607. }
  87608. };
  87609. this.beforeRender = function () {
  87610. if (_this.leftController && _this.leftController._activePointer) {
  87611. _this._castRayAndSelectObject(_this.leftController);
  87612. }
  87613. if (_this.rightController && _this.rightController._activePointer) {
  87614. _this._castRayAndSelectObject(_this.rightController);
  87615. }
  87616. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87617. _this._castRayAndSelectObject(_this._cameraGazer);
  87618. }
  87619. else {
  87620. _this._cameraGazer._gazeTracker.isVisible = false;
  87621. }
  87622. };
  87623. this._onNewGamepadConnected = function (gamepad) {
  87624. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87625. if (gamepad.leftStick) {
  87626. gamepad.onleftstickchanged(function (stickValues) {
  87627. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87628. // Listening to classic/xbox gamepad only if no VR controller is active
  87629. if ((!_this.leftController && !_this.rightController) ||
  87630. ((_this.leftController && !_this.leftController._activePointer) &&
  87631. (_this.rightController && !_this.rightController._activePointer))) {
  87632. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87633. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87634. }
  87635. }
  87636. });
  87637. }
  87638. if (gamepad.rightStick) {
  87639. gamepad.onrightstickchanged(function (stickValues) {
  87640. if (_this._teleportationInitialized) {
  87641. _this._checkRotate(stickValues, _this._cameraGazer);
  87642. }
  87643. });
  87644. }
  87645. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87646. gamepad.onbuttondown(function (buttonPressed) {
  87647. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87648. _this._cameraGazer._selectionPointerDown();
  87649. }
  87650. });
  87651. gamepad.onbuttonup(function (buttonPressed) {
  87652. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87653. _this._cameraGazer._selectionPointerUp();
  87654. }
  87655. });
  87656. }
  87657. }
  87658. else {
  87659. var webVRController = gamepad;
  87660. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87661. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87662. _this.rightController = controller;
  87663. }
  87664. else {
  87665. _this.leftController = controller;
  87666. }
  87667. _this._tryEnableInteractionOnController(controller);
  87668. }
  87669. };
  87670. // 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
  87671. this._tryEnableInteractionOnController = function (controller) {
  87672. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87673. _this._enableInteractionOnController(controller);
  87674. }
  87675. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87676. _this._enableTeleportationOnController(controller);
  87677. }
  87678. };
  87679. this._onNewGamepadDisconnected = function (gamepad) {
  87680. if (gamepad instanceof BABYLON.WebVRController) {
  87681. if (gamepad.hand === "left" && _this.leftController != null) {
  87682. _this.leftController.dispose();
  87683. _this.leftController = null;
  87684. }
  87685. if (gamepad.hand === "right" && _this.rightController != null) {
  87686. _this.rightController.dispose();
  87687. _this.rightController = null;
  87688. }
  87689. }
  87690. };
  87691. this._workingVector = BABYLON.Vector3.Zero();
  87692. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87693. this._workingMatrix = BABYLON.Matrix.Identity();
  87694. this._scene = scene;
  87695. this._canvas = scene.getEngine().getRenderingCanvas();
  87696. // Parse options
  87697. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87698. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87699. }
  87700. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87701. webVROptions.createDeviceOrientationCamera = true;
  87702. }
  87703. if (webVROptions.defaultHeight === undefined) {
  87704. webVROptions.defaultHeight = 1.7;
  87705. }
  87706. if (webVROptions.useCustomVRButton) {
  87707. this._useCustomVRButton = true;
  87708. if (webVROptions.customVRButton) {
  87709. this._btnVR = webVROptions.customVRButton;
  87710. }
  87711. }
  87712. if (webVROptions.rayLength) {
  87713. this._rayLength = webVROptions.rayLength;
  87714. }
  87715. this._defaultHeight = webVROptions.defaultHeight;
  87716. if (webVROptions.positionScale) {
  87717. this._rayLength *= webVROptions.positionScale;
  87718. this._defaultHeight *= webVROptions.positionScale;
  87719. }
  87720. // Set position
  87721. if (this._scene.activeCamera) {
  87722. this._position = this._scene.activeCamera.position.clone();
  87723. }
  87724. else {
  87725. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87726. }
  87727. // Set non-vr camera
  87728. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87729. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87730. // Copy data from existing camera
  87731. if (this._scene.activeCamera) {
  87732. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87733. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87734. // Set rotation from previous camera
  87735. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87736. var targetCamera = this._scene.activeCamera;
  87737. if (targetCamera.rotationQuaternion) {
  87738. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87739. }
  87740. else {
  87741. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87742. }
  87743. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87744. }
  87745. }
  87746. this._scene.activeCamera = this._deviceOrientationCamera;
  87747. if (this._canvas) {
  87748. this._scene.activeCamera.attachControl(this._canvas);
  87749. }
  87750. }
  87751. else {
  87752. this._existingCamera = this._scene.activeCamera;
  87753. }
  87754. // Create VR cameras
  87755. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87756. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87757. }
  87758. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87759. this._webVRCamera.useStandingMatrix();
  87760. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87761. // Create default button
  87762. if (!this._useCustomVRButton) {
  87763. this._btnVR = document.createElement("BUTTON");
  87764. this._btnVR.className = "babylonVRicon";
  87765. this._btnVR.id = "babylonVRiconbtn";
  87766. this._btnVR.title = "Click to switch to VR";
  87767. 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) }";
  87768. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87769. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87770. // css += ".babylonVRicon.vrdisplaysupported { }";
  87771. // css += ".babylonVRicon.vrdisplayready { }";
  87772. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87773. var style = document.createElement('style');
  87774. style.appendChild(document.createTextNode(css));
  87775. document.getElementsByTagName('head')[0].appendChild(style);
  87776. this.moveButtonToBottomRight();
  87777. }
  87778. // VR button click event
  87779. if (this._btnVR) {
  87780. this._btnVR.addEventListener("click", function () {
  87781. if (!_this.isInVRMode) {
  87782. _this.enterVR();
  87783. }
  87784. else {
  87785. _this.exitVR();
  87786. }
  87787. });
  87788. }
  87789. // Window events
  87790. window.addEventListener("resize", this._onResize);
  87791. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87792. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87793. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87794. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87795. // Display vr button when headset is connected
  87796. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87797. this.displayVRButton();
  87798. }
  87799. else {
  87800. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87801. if (e.vrDisplay) {
  87802. _this.displayVRButton();
  87803. }
  87804. });
  87805. }
  87806. // Exiting VR mode using 'ESC' key on desktop
  87807. this._onKeyDown = function (event) {
  87808. if (event.keyCode === 27 && _this.isInVRMode) {
  87809. _this.exitVR();
  87810. }
  87811. };
  87812. document.addEventListener("keydown", this._onKeyDown);
  87813. // Exiting VR mode double tapping the touch screen
  87814. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87815. if (_this.isInVRMode) {
  87816. _this.exitVR();
  87817. if (_this._fullscreenVRpresenting) {
  87818. _this._scene.getEngine().switchFullscreen(true);
  87819. }
  87820. }
  87821. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87822. // Listen for WebVR display changes
  87823. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87824. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87825. this._onVRRequestPresentStart = function () {
  87826. _this._webVRrequesting = true;
  87827. _this.updateButtonVisibility();
  87828. };
  87829. this._onVRRequestPresentComplete = function (success) {
  87830. _this._webVRrequesting = false;
  87831. _this.updateButtonVisibility();
  87832. };
  87833. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87834. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87835. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87836. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87837. scene.onDisposeObservable.add(function () {
  87838. _this.dispose();
  87839. });
  87840. // Gamepad connection events
  87841. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87842. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87843. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87844. this.updateButtonVisibility();
  87845. //create easing functions
  87846. this._circleEase = new BABYLON.CircleEase();
  87847. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87848. }
  87849. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87850. /** Return this.onEnteringVRObservable
  87851. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87852. */
  87853. get: function () {
  87854. return this.onEnteringVRObservable;
  87855. },
  87856. enumerable: true,
  87857. configurable: true
  87858. });
  87859. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87860. /** Return this.onExitingVRObservable
  87861. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87862. */
  87863. get: function () {
  87864. return this.onExitingVRObservable;
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87870. /** Return this.onControllerMeshLoadedObservable
  87871. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87872. */
  87873. get: function () {
  87874. return this.onControllerMeshLoadedObservable;
  87875. },
  87876. enumerable: true,
  87877. configurable: true
  87878. });
  87879. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87880. /**
  87881. * The mesh used to display where the user is going to teleport.
  87882. */
  87883. get: function () {
  87884. return this._teleportationTarget;
  87885. },
  87886. /**
  87887. * Sets the mesh to be used to display where the user is going to teleport.
  87888. */
  87889. set: function (value) {
  87890. if (value) {
  87891. value.name = "teleportationTarget";
  87892. this._isDefaultTeleportationTarget = false;
  87893. this._teleportationTarget = value;
  87894. }
  87895. },
  87896. enumerable: true,
  87897. configurable: true
  87898. });
  87899. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87900. /**
  87901. * The mesh used to display where the user is selecting,
  87902. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87903. * See http://doc.babylonjs.com/resources/baking_transformations
  87904. */
  87905. get: function () {
  87906. return this._cameraGazer._gazeTracker;
  87907. },
  87908. set: function (value) {
  87909. if (value) {
  87910. this._cameraGazer._gazeTracker = value;
  87911. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87912. this._cameraGazer._gazeTracker.isPickable = false;
  87913. this._cameraGazer._gazeTracker.isVisible = false;
  87914. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87915. if (this.leftController) {
  87916. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87917. }
  87918. if (this.rightController) {
  87919. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87920. }
  87921. }
  87922. },
  87923. enumerable: true,
  87924. configurable: true
  87925. });
  87926. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87927. /**
  87928. * If the ray of the gaze should be displayed.
  87929. */
  87930. get: function () {
  87931. return this._displayGaze;
  87932. },
  87933. /**
  87934. * Sets if the ray of the gaze should be displayed.
  87935. */
  87936. set: function (value) {
  87937. this._displayGaze = value;
  87938. if (!value) {
  87939. this._cameraGazer._gazeTracker.isVisible = false;
  87940. if (this.leftController) {
  87941. this.leftController._gazeTracker.isVisible = false;
  87942. }
  87943. if (this.rightController) {
  87944. this.rightController._gazeTracker.isVisible = false;
  87945. }
  87946. }
  87947. },
  87948. enumerable: true,
  87949. configurable: true
  87950. });
  87951. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87952. /**
  87953. * If the ray of the LaserPointer should be displayed.
  87954. */
  87955. get: function () {
  87956. return this._displayLaserPointer;
  87957. },
  87958. /**
  87959. * Sets if the ray of the LaserPointer should be displayed.
  87960. */
  87961. set: function (value) {
  87962. this._displayLaserPointer = value;
  87963. if (!value) {
  87964. if (this.rightController) {
  87965. this.rightController._deactivatePointer();
  87966. this.rightController._gazeTracker.isVisible = false;
  87967. }
  87968. if (this.leftController) {
  87969. this.leftController._deactivatePointer();
  87970. this.leftController._gazeTracker.isVisible = false;
  87971. }
  87972. }
  87973. else {
  87974. if (this.rightController) {
  87975. this.rightController._activatePointer();
  87976. }
  87977. if (this.leftController) {
  87978. this.leftController._activatePointer();
  87979. }
  87980. }
  87981. },
  87982. enumerable: true,
  87983. configurable: true
  87984. });
  87985. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87986. /**
  87987. * The deviceOrientationCamera used as the camera when not in VR.
  87988. */
  87989. get: function () {
  87990. return this._deviceOrientationCamera;
  87991. },
  87992. enumerable: true,
  87993. configurable: true
  87994. });
  87995. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87996. /**
  87997. * Based on the current WebVR support, returns the current VR camera used.
  87998. */
  87999. get: function () {
  88000. if (this._webVRready) {
  88001. return this._webVRCamera;
  88002. }
  88003. else {
  88004. return this._scene.activeCamera;
  88005. }
  88006. },
  88007. enumerable: true,
  88008. configurable: true
  88009. });
  88010. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88011. /**
  88012. * The webVRCamera which is used when in VR.
  88013. */
  88014. get: function () {
  88015. return this._webVRCamera;
  88016. },
  88017. enumerable: true,
  88018. configurable: true
  88019. });
  88020. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88021. /**
  88022. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88023. */
  88024. get: function () {
  88025. return this._vrDeviceOrientationCamera;
  88026. },
  88027. enumerable: true,
  88028. configurable: true
  88029. });
  88030. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88031. get: function () {
  88032. var result = this._cameraGazer._teleportationRequestInitiated
  88033. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88034. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88035. return result;
  88036. },
  88037. enumerable: true,
  88038. configurable: true
  88039. });
  88040. // Raised when one of the controller has loaded successfully its associated default mesh
  88041. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88042. if (this.leftController && this.leftController.webVRController == webVRController) {
  88043. if (webVRController.mesh) {
  88044. this.leftController._setLaserPointerParent(webVRController.mesh);
  88045. }
  88046. }
  88047. if (this.rightController && this.rightController.webVRController == webVRController) {
  88048. if (webVRController.mesh) {
  88049. this.rightController._setLaserPointerParent(webVRController.mesh);
  88050. }
  88051. }
  88052. try {
  88053. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88054. }
  88055. catch (err) {
  88056. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88057. }
  88058. };
  88059. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88060. /**
  88061. * Gets a value indicating if we are currently in VR mode.
  88062. */
  88063. get: function () {
  88064. return this._webVRpresenting || this._fullscreenVRpresenting;
  88065. },
  88066. enumerable: true,
  88067. configurable: true
  88068. });
  88069. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88070. var vrDisplay = this._scene.getEngine().getVRDevice();
  88071. if (vrDisplay) {
  88072. var wasPresenting = this._webVRpresenting;
  88073. // A VR display is connected
  88074. this._webVRpresenting = vrDisplay.isPresenting;
  88075. if (wasPresenting && !this._webVRpresenting)
  88076. this.exitVR();
  88077. }
  88078. else {
  88079. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88080. }
  88081. this.updateButtonVisibility();
  88082. };
  88083. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88084. this._webVRsupported = eventArgs.vrSupported;
  88085. this._webVRready = !!eventArgs.vrDisplay;
  88086. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88087. this.updateButtonVisibility();
  88088. };
  88089. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88090. if (this._canvas && !this._useCustomVRButton) {
  88091. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88092. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88093. }
  88094. };
  88095. VRExperienceHelper.prototype.displayVRButton = function () {
  88096. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88097. document.body.appendChild(this._btnVR);
  88098. this._btnVRDisplayed = true;
  88099. }
  88100. };
  88101. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88102. if (!this._btnVR || this._useCustomVRButton) {
  88103. return;
  88104. }
  88105. this._btnVR.className = "babylonVRicon";
  88106. if (this.isInVRMode) {
  88107. this._btnVR.className += " vrdisplaypresenting";
  88108. }
  88109. else {
  88110. if (this._webVRready)
  88111. this._btnVR.className += " vrdisplayready";
  88112. if (this._webVRsupported)
  88113. this._btnVR.className += " vrdisplaysupported";
  88114. if (this._webVRrequesting)
  88115. this._btnVR.className += " vrdisplayrequesting";
  88116. }
  88117. };
  88118. /**
  88119. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88120. * Otherwise, will use the fullscreen API.
  88121. */
  88122. VRExperienceHelper.prototype.enterVR = function () {
  88123. if (this.onEnteringVRObservable) {
  88124. try {
  88125. this.onEnteringVRObservable.notifyObservers(this);
  88126. }
  88127. catch (err) {
  88128. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88129. }
  88130. }
  88131. if (this._scene.activeCamera) {
  88132. this._position = this._scene.activeCamera.position.clone();
  88133. // make sure that we return to the last active camera
  88134. this._existingCamera = this._scene.activeCamera;
  88135. }
  88136. if (this._webVRrequesting)
  88137. return;
  88138. // If WebVR is supported and a headset is connected
  88139. if (this._webVRready) {
  88140. if (!this._webVRpresenting) {
  88141. this._webVRCamera.position = this._position;
  88142. this._scene.activeCamera = this._webVRCamera;
  88143. }
  88144. }
  88145. else if (this._vrDeviceOrientationCamera) {
  88146. this._vrDeviceOrientationCamera.position = this._position;
  88147. if (this._scene.activeCamera) {
  88148. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88149. }
  88150. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88151. this._scene.getEngine().switchFullscreen(true);
  88152. this.updateButtonVisibility();
  88153. }
  88154. if (this._scene.activeCamera && this._canvas) {
  88155. this._scene.activeCamera.attachControl(this._canvas);
  88156. }
  88157. if (this._interactionsEnabled) {
  88158. this._scene.registerBeforeRender(this.beforeRender);
  88159. }
  88160. };
  88161. /**
  88162. * Attempt to exit VR, or fullscreen.
  88163. */
  88164. VRExperienceHelper.prototype.exitVR = function () {
  88165. if (this.onExitingVRObservable) {
  88166. try {
  88167. this.onExitingVRObservable.notifyObservers(this);
  88168. }
  88169. catch (err) {
  88170. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88171. }
  88172. }
  88173. if (this._webVRpresenting) {
  88174. this._scene.getEngine().disableVR();
  88175. }
  88176. if (this._scene.activeCamera) {
  88177. this._position = this._scene.activeCamera.position.clone();
  88178. }
  88179. if (this._deviceOrientationCamera) {
  88180. this._deviceOrientationCamera.position = this._position;
  88181. this._scene.activeCamera = this._deviceOrientationCamera;
  88182. if (this._canvas) {
  88183. this._scene.activeCamera.attachControl(this._canvas);
  88184. }
  88185. }
  88186. else if (this._existingCamera) {
  88187. this._existingCamera.position = this._position;
  88188. this._scene.activeCamera = this._existingCamera;
  88189. }
  88190. this.updateButtonVisibility();
  88191. if (this._interactionsEnabled) {
  88192. this._scene.unregisterBeforeRender(this.beforeRender);
  88193. }
  88194. // resize to update width and height when exiting vr exits fullscreen
  88195. this._scene.getEngine().resize();
  88196. };
  88197. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88198. /**
  88199. * The position of the vr experience helper.
  88200. */
  88201. get: function () {
  88202. return this._position;
  88203. },
  88204. /**
  88205. * Sets the position of the vr experience helper.
  88206. */
  88207. set: function (value) {
  88208. this._position = value;
  88209. if (this._scene.activeCamera) {
  88210. this._scene.activeCamera.position = value;
  88211. }
  88212. },
  88213. enumerable: true,
  88214. configurable: true
  88215. });
  88216. /**
  88217. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88218. */
  88219. VRExperienceHelper.prototype.enableInteractions = function () {
  88220. var _this = this;
  88221. if (!this._interactionsEnabled) {
  88222. this._interactionsRequested = true;
  88223. if (this.leftController) {
  88224. this._enableInteractionOnController(this.leftController);
  88225. }
  88226. if (this.rightController) {
  88227. this._enableInteractionOnController(this.rightController);
  88228. }
  88229. this.raySelectionPredicate = function (mesh) {
  88230. return mesh.isVisible;
  88231. };
  88232. this.meshSelectionPredicate = function (mesh) {
  88233. return true;
  88234. };
  88235. this._raySelectionPredicate = function (mesh) {
  88236. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88237. && mesh.name.indexOf("teleportationTarget") === -1
  88238. && mesh.name.indexOf("torusTeleportation") === -1
  88239. && mesh.name.indexOf("laserPointer") === -1)) {
  88240. return _this.raySelectionPredicate(mesh);
  88241. }
  88242. return false;
  88243. };
  88244. this._interactionsEnabled = true;
  88245. }
  88246. };
  88247. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88248. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88249. if (this._floorMeshesCollection[i].id === mesh.id) {
  88250. return true;
  88251. }
  88252. }
  88253. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88254. return true;
  88255. }
  88256. return false;
  88257. };
  88258. /**
  88259. * Adds a floor mesh to be used for teleportation.
  88260. * @param floorMesh the mesh to be used for teleportation.
  88261. */
  88262. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88263. if (!this._floorMeshesCollection) {
  88264. return;
  88265. }
  88266. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88267. return;
  88268. }
  88269. this._floorMeshesCollection.push(floorMesh);
  88270. };
  88271. /**
  88272. * Removes a floor mesh from being used for teleportation.
  88273. * @param floorMesh the mesh to be removed.
  88274. */
  88275. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88276. if (!this._floorMeshesCollection) {
  88277. return;
  88278. }
  88279. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88280. if (meshIndex !== -1) {
  88281. this._floorMeshesCollection.splice(meshIndex, 1);
  88282. }
  88283. };
  88284. /**
  88285. * Enables interactions and teleportation using the VR controllers and gaze.
  88286. * @param vrTeleportationOptions options to modify teleportation behavior.
  88287. */
  88288. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88289. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88290. if (!this._teleportationInitialized) {
  88291. this._teleportationRequested = true;
  88292. this.enableInteractions();
  88293. if (vrTeleportationOptions.floorMeshName) {
  88294. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88295. }
  88296. if (vrTeleportationOptions.floorMeshes) {
  88297. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88298. }
  88299. if (this.leftController != null) {
  88300. this._enableTeleportationOnController(this.leftController);
  88301. }
  88302. if (this.rightController != null) {
  88303. this._enableTeleportationOnController(this.rightController);
  88304. }
  88305. // Creates an image processing post process for the vignette not relying
  88306. // on the main scene configuration for image processing to reduce setup and spaces
  88307. // (gamma/linear) conflicts.
  88308. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88309. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88310. imageProcessingConfiguration.vignetteEnabled = true;
  88311. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88312. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88313. this._teleportationInitialized = true;
  88314. if (this._isDefaultTeleportationTarget) {
  88315. this._createTeleportationCircles();
  88316. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88317. }
  88318. }
  88319. };
  88320. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88321. var _this = this;
  88322. var controllerMesh = controller.webVRController.mesh;
  88323. if (controllerMesh) {
  88324. controller._interactionsEnabled = true;
  88325. controller._activatePointer();
  88326. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88327. // Enabling / disabling laserPointer
  88328. if (_this._displayLaserPointer && stateObject.value === 1) {
  88329. if (controller._activePointer) {
  88330. controller._deactivatePointer();
  88331. }
  88332. else {
  88333. controller._activatePointer();
  88334. }
  88335. if (_this.displayGaze) {
  88336. controller._gazeTracker.isVisible = controller._activePointer;
  88337. }
  88338. }
  88339. });
  88340. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88341. if (!controller._pointerDownOnMeshAsked) {
  88342. if (stateObject.value > _this._padSensibilityUp) {
  88343. controller._selectionPointerDown();
  88344. }
  88345. }
  88346. else if (stateObject.value < _this._padSensibilityDown) {
  88347. controller._selectionPointerUp();
  88348. }
  88349. });
  88350. }
  88351. };
  88352. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88353. // Dont teleport if another gaze already requested teleportation
  88354. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88355. return;
  88356. }
  88357. if (!gazer._teleportationRequestInitiated) {
  88358. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88359. gazer._activatePointer();
  88360. gazer._teleportationRequestInitiated = true;
  88361. }
  88362. }
  88363. else {
  88364. // Listening to the proper controller values changes to confirm teleportation
  88365. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88366. if (this._teleportActive) {
  88367. this._teleportCamera(this._haloCenter);
  88368. }
  88369. gazer._teleportationRequestInitiated = false;
  88370. }
  88371. }
  88372. };
  88373. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88374. // Only rotate when user is not currently selecting a teleportation location
  88375. if (gazer._teleportationRequestInitiated) {
  88376. return;
  88377. }
  88378. if (!gazer._rotationLeftAsked) {
  88379. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88380. gazer._rotationLeftAsked = true;
  88381. if (this._rotationAllowed) {
  88382. this._rotateCamera(false);
  88383. }
  88384. }
  88385. }
  88386. else {
  88387. if (stateObject.x > -this._padSensibilityDown) {
  88388. gazer._rotationLeftAsked = false;
  88389. }
  88390. }
  88391. if (!gazer._rotationRightAsked) {
  88392. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88393. gazer._rotationRightAsked = true;
  88394. if (this._rotationAllowed) {
  88395. this._rotateCamera(true);
  88396. }
  88397. }
  88398. }
  88399. else {
  88400. if (stateObject.x < this._padSensibilityDown) {
  88401. gazer._rotationRightAsked = false;
  88402. }
  88403. }
  88404. };
  88405. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88406. // Only teleport backwards when user is not currently selecting a teleportation location
  88407. if (gazer._teleportationRequestInitiated) {
  88408. return;
  88409. }
  88410. // Teleport backwards
  88411. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88412. if (!gazer._teleportationBackRequestInitiated) {
  88413. if (!this.currentVRCamera) {
  88414. return;
  88415. }
  88416. // Get rotation and position of the current camera
  88417. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88418. var position = this.currentVRCamera.position;
  88419. // If the camera has device position, use that instead
  88420. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88421. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88422. position = this.currentVRCamera.devicePosition;
  88423. }
  88424. // Get matrix with only the y rotation of the device rotation
  88425. rotation.toEulerAnglesToRef(this._workingVector);
  88426. this._workingVector.z = 0;
  88427. this._workingVector.x = 0;
  88428. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88429. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88430. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88431. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88432. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88433. var ray = new BABYLON.Ray(position, this._workingVector);
  88434. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88435. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88436. this._teleportCamera(hit.pickedPoint);
  88437. }
  88438. gazer._teleportationBackRequestInitiated = true;
  88439. }
  88440. }
  88441. else {
  88442. gazer._teleportationBackRequestInitiated = false;
  88443. }
  88444. };
  88445. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88446. var _this = this;
  88447. var controllerMesh = controller.webVRController.mesh;
  88448. if (controllerMesh) {
  88449. if (!controller._interactionsEnabled) {
  88450. this._enableInteractionOnController(controller);
  88451. }
  88452. controller._interactionsEnabled = true;
  88453. controller._teleportationEnabled = true;
  88454. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88455. controller._dpadPressed = false;
  88456. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88457. controller._dpadPressed = stateObject.pressed;
  88458. if (!controller._dpadPressed) {
  88459. controller._rotationLeftAsked = false;
  88460. controller._rotationRightAsked = false;
  88461. controller._teleportationBackRequestInitiated = false;
  88462. }
  88463. });
  88464. }
  88465. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88466. if (_this.teleportationEnabled) {
  88467. _this._checkTeleportBackwards(stateObject, controller);
  88468. _this._checkTeleportWithRay(stateObject, controller);
  88469. }
  88470. _this._checkRotate(stateObject, controller);
  88471. });
  88472. }
  88473. };
  88474. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88475. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88476. this._teleportationTarget.isPickable = false;
  88477. var length = 512;
  88478. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88479. dynamicTexture.hasAlpha = true;
  88480. var context = dynamicTexture.getContext();
  88481. var centerX = length / 2;
  88482. var centerY = length / 2;
  88483. var radius = 200;
  88484. context.beginPath();
  88485. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88486. context.fillStyle = this._teleportationFillColor;
  88487. context.fill();
  88488. context.lineWidth = 10;
  88489. context.strokeStyle = this._teleportationBorderColor;
  88490. context.stroke();
  88491. context.closePath();
  88492. dynamicTexture.update();
  88493. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88494. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88495. this._teleportationTarget.material = teleportationCircleMaterial;
  88496. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88497. torus.isPickable = false;
  88498. torus.parent = this._teleportationTarget;
  88499. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88500. var keys = [];
  88501. keys.push({
  88502. frame: 0,
  88503. value: 0
  88504. });
  88505. keys.push({
  88506. frame: 30,
  88507. value: 0.4
  88508. });
  88509. keys.push({
  88510. frame: 60,
  88511. value: 0
  88512. });
  88513. animationInnerCircle.setKeys(keys);
  88514. var easingFunction = new BABYLON.SineEase();
  88515. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88516. animationInnerCircle.setEasingFunction(easingFunction);
  88517. torus.animations = [];
  88518. torus.animations.push(animationInnerCircle);
  88519. this._scene.beginAnimation(torus, 0, 60, true);
  88520. this._hideTeleportationTarget();
  88521. };
  88522. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88523. this._teleportActive = true;
  88524. if (this._teleportationInitialized) {
  88525. this._teleportationTarget.isVisible = true;
  88526. if (this._isDefaultTeleportationTarget) {
  88527. this._teleportationTarget.getChildren()[0].isVisible = true;
  88528. }
  88529. }
  88530. };
  88531. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88532. this._teleportActive = false;
  88533. if (this._teleportationInitialized) {
  88534. this._teleportationTarget.isVisible = false;
  88535. if (this._isDefaultTeleportationTarget) {
  88536. this._teleportationTarget.getChildren()[0].isVisible = false;
  88537. }
  88538. }
  88539. };
  88540. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88541. var _this = this;
  88542. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88543. return;
  88544. }
  88545. if (right) {
  88546. this._rotationAngle++;
  88547. }
  88548. else {
  88549. this._rotationAngle--;
  88550. }
  88551. this.currentVRCamera.animations = [];
  88552. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88553. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88554. var animationRotationKeys = [];
  88555. animationRotationKeys.push({
  88556. frame: 0,
  88557. value: this.currentVRCamera.rotationQuaternion
  88558. });
  88559. animationRotationKeys.push({
  88560. frame: 6,
  88561. value: target
  88562. });
  88563. animationRotation.setKeys(animationRotationKeys);
  88564. animationRotation.setEasingFunction(this._circleEase);
  88565. this.currentVRCamera.animations.push(animationRotation);
  88566. this._postProcessMove.animations = [];
  88567. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88568. var vignetteWeightKeys = [];
  88569. vignetteWeightKeys.push({
  88570. frame: 0,
  88571. value: 0
  88572. });
  88573. vignetteWeightKeys.push({
  88574. frame: 3,
  88575. value: 4
  88576. });
  88577. vignetteWeightKeys.push({
  88578. frame: 6,
  88579. value: 0
  88580. });
  88581. animationPP.setKeys(vignetteWeightKeys);
  88582. animationPP.setEasingFunction(this._circleEase);
  88583. this._postProcessMove.animations.push(animationPP);
  88584. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88585. var vignetteStretchKeys = [];
  88586. vignetteStretchKeys.push({
  88587. frame: 0,
  88588. value: 0
  88589. });
  88590. vignetteStretchKeys.push({
  88591. frame: 3,
  88592. value: 10
  88593. });
  88594. vignetteStretchKeys.push({
  88595. frame: 6,
  88596. value: 0
  88597. });
  88598. animationPP2.setKeys(vignetteStretchKeys);
  88599. animationPP2.setEasingFunction(this._circleEase);
  88600. this._postProcessMove.animations.push(animationPP2);
  88601. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88602. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88603. this._postProcessMove.samples = 4;
  88604. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88605. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88606. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88607. });
  88608. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88609. };
  88610. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88611. if (hit.pickedPoint) {
  88612. if (gazer._teleportationRequestInitiated) {
  88613. this._displayTeleportationTarget();
  88614. this._haloCenter.copyFrom(hit.pickedPoint);
  88615. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88616. }
  88617. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88618. if (pickNormal) {
  88619. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88620. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88621. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88622. }
  88623. this._teleportationTarget.position.y += 0.1;
  88624. }
  88625. };
  88626. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88627. var _this = this;
  88628. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88629. return;
  88630. }
  88631. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88632. // offset of the headset from the anchor.
  88633. if (this.webVRCamera.leftCamera) {
  88634. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88635. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88636. location.subtractToRef(this._workingVector, this._workingVector);
  88637. }
  88638. else {
  88639. this._workingVector.copyFrom(location);
  88640. }
  88641. // Add height to account for user's height offset
  88642. if (this.isInVRMode) {
  88643. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88644. }
  88645. else {
  88646. this._workingVector.y += this._defaultHeight;
  88647. }
  88648. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88649. // Create animation from the camera's position to the new location
  88650. this.currentVRCamera.animations = [];
  88651. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88652. var animationCameraTeleportationKeys = [{
  88653. frame: 0,
  88654. value: this.currentVRCamera.position
  88655. },
  88656. {
  88657. frame: 11,
  88658. value: this._workingVector
  88659. }
  88660. ];
  88661. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88662. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88663. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88664. this._postProcessMove.animations = [];
  88665. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88666. var vignetteWeightKeys = [];
  88667. vignetteWeightKeys.push({
  88668. frame: 0,
  88669. value: 0
  88670. });
  88671. vignetteWeightKeys.push({
  88672. frame: 5,
  88673. value: 8
  88674. });
  88675. vignetteWeightKeys.push({
  88676. frame: 11,
  88677. value: 0
  88678. });
  88679. animationPP.setKeys(vignetteWeightKeys);
  88680. this._postProcessMove.animations.push(animationPP);
  88681. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88682. var vignetteStretchKeys = [];
  88683. vignetteStretchKeys.push({
  88684. frame: 0,
  88685. value: 0
  88686. });
  88687. vignetteStretchKeys.push({
  88688. frame: 5,
  88689. value: 10
  88690. });
  88691. vignetteStretchKeys.push({
  88692. frame: 11,
  88693. value: 0
  88694. });
  88695. animationPP2.setKeys(vignetteStretchKeys);
  88696. this._postProcessMove.animations.push(animationPP2);
  88697. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88698. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88699. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88700. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88701. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88702. });
  88703. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88704. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88705. });
  88706. this._hideTeleportationTarget();
  88707. };
  88708. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88709. if (normal) {
  88710. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88711. if (angle < Math.PI / 2) {
  88712. normal.scaleInPlace(-1);
  88713. }
  88714. }
  88715. return normal;
  88716. };
  88717. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88718. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88719. return;
  88720. }
  88721. var ray = gazer._getForwardRay(this._rayLength);
  88722. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88723. // Moving the gazeTracker on the mesh face targetted
  88724. if (hit && hit.pickedPoint) {
  88725. if (this._displayGaze) {
  88726. var multiplier = 1;
  88727. gazer._gazeTracker.isVisible = true;
  88728. if (gazer._isActionableMesh) {
  88729. multiplier = 3;
  88730. }
  88731. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88732. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88733. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88734. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88735. // To avoid z-fighting
  88736. var deltaFighting = 0.002;
  88737. if (pickNormal) {
  88738. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88739. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88740. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88741. }
  88742. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88743. if (gazer._gazeTracker.position.x < 0) {
  88744. gazer._gazeTracker.position.x += deltaFighting;
  88745. }
  88746. else {
  88747. gazer._gazeTracker.position.x -= deltaFighting;
  88748. }
  88749. if (gazer._gazeTracker.position.y < 0) {
  88750. gazer._gazeTracker.position.y += deltaFighting;
  88751. }
  88752. else {
  88753. gazer._gazeTracker.position.y -= deltaFighting;
  88754. }
  88755. if (gazer._gazeTracker.position.z < 0) {
  88756. gazer._gazeTracker.position.z += deltaFighting;
  88757. }
  88758. else {
  88759. gazer._gazeTracker.position.z -= deltaFighting;
  88760. }
  88761. }
  88762. // Changing the size of the laser pointer based on the distance from the targetted point
  88763. gazer._updatePointerDistance(hit.distance);
  88764. }
  88765. else {
  88766. gazer._updatePointerDistance();
  88767. gazer._gazeTracker.isVisible = false;
  88768. }
  88769. if (hit && hit.pickedMesh) {
  88770. gazer._currentHit = hit;
  88771. if (gazer._pointerDownOnMeshAsked) {
  88772. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88773. }
  88774. // The object selected is the floor, we're in a teleportation scenario
  88775. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88776. // Moving the teleportation area to this targetted point
  88777. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88778. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88779. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88780. }
  88781. gazer._currentMeshSelected = null;
  88782. if (gazer._teleportationRequestInitiated) {
  88783. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88784. }
  88785. return;
  88786. }
  88787. // If not, we're in a selection scenario
  88788. //this._teleportationAllowed = false;
  88789. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88790. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88791. this.onNewMeshPicked.notifyObservers(hit);
  88792. gazer._currentMeshSelected = hit.pickedMesh;
  88793. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88794. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88795. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88796. gazer._isActionableMesh = true;
  88797. }
  88798. else {
  88799. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88800. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88801. gazer._isActionableMesh = false;
  88802. }
  88803. try {
  88804. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88805. }
  88806. catch (err) {
  88807. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88808. }
  88809. }
  88810. else {
  88811. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88812. gazer._currentMeshSelected = null;
  88813. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88814. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88815. }
  88816. }
  88817. }
  88818. else {
  88819. gazer._currentHit = null;
  88820. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88821. gazer._currentMeshSelected = null;
  88822. //this._teleportationAllowed = false;
  88823. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88824. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88825. }
  88826. };
  88827. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88828. if (mesh) {
  88829. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88830. }
  88831. };
  88832. /**
  88833. * Sets the color of the laser ray from the vr controllers.
  88834. * @param color new color for the ray.
  88835. */
  88836. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88837. if (this.leftController) {
  88838. this.leftController._setLaserPointerColor(color);
  88839. }
  88840. if (this.rightController) {
  88841. this.rightController._setLaserPointerColor(color);
  88842. }
  88843. };
  88844. /**
  88845. * Sets the color of the ray from the vr headsets gaze.
  88846. * @param color new color for the ray.
  88847. */
  88848. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88849. if (!this._cameraGazer._gazeTracker.material) {
  88850. return;
  88851. }
  88852. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88853. if (this.leftController) {
  88854. this.leftController._gazeTracker.material.emissiveColor = color;
  88855. }
  88856. if (this.rightController) {
  88857. this.rightController._gazeTracker.material.emissiveColor = color;
  88858. }
  88859. };
  88860. /**
  88861. * Exits VR and disposes of the vr experience helper
  88862. */
  88863. VRExperienceHelper.prototype.dispose = function () {
  88864. if (this.isInVRMode) {
  88865. this.exitVR();
  88866. }
  88867. if (this._postProcessMove) {
  88868. this._postProcessMove.dispose();
  88869. }
  88870. if (this._webVRCamera) {
  88871. this._webVRCamera.dispose();
  88872. }
  88873. if (this._vrDeviceOrientationCamera) {
  88874. this._vrDeviceOrientationCamera.dispose();
  88875. }
  88876. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88877. document.body.removeChild(this._btnVR);
  88878. }
  88879. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88880. this._deviceOrientationCamera.dispose();
  88881. }
  88882. if (this._cameraGazer) {
  88883. this._cameraGazer.dispose();
  88884. }
  88885. if (this.leftController) {
  88886. this.leftController.dispose();
  88887. }
  88888. if (this.rightController) {
  88889. this.rightController.dispose();
  88890. }
  88891. if (this._teleportationTarget) {
  88892. this._teleportationTarget.dispose();
  88893. }
  88894. this._floorMeshesCollection = [];
  88895. document.removeEventListener("keydown", this._onKeyDown);
  88896. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88897. window.removeEventListener("resize", this._onResize);
  88898. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88899. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88900. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88901. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88902. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88903. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88904. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88905. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88906. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88907. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88908. this._scene.unregisterBeforeRender(this.beforeRender);
  88909. };
  88910. /**
  88911. * Gets the name of the VRExperienceHelper class
  88912. * @returns "VRExperienceHelper"
  88913. */
  88914. VRExperienceHelper.prototype.getClassName = function () {
  88915. return "VRExperienceHelper";
  88916. };
  88917. return VRExperienceHelper;
  88918. }());
  88919. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88920. })(BABYLON || (BABYLON = {}));
  88921. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88922. // Mainly based on these 2 articles :
  88923. // 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
  88924. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88925. var BABYLON;
  88926. (function (BABYLON) {
  88927. /**
  88928. * Defines the potential axis of a Joystick
  88929. */
  88930. var JoystickAxis;
  88931. (function (JoystickAxis) {
  88932. /** X axis */
  88933. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88934. /** Y axis */
  88935. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88936. /** Z axis */
  88937. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88938. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88939. /**
  88940. * Class used to define virtual joystick (used in touch mode)
  88941. */
  88942. var VirtualJoystick = /** @class */ (function () {
  88943. /**
  88944. * Creates a new virtual joystick
  88945. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88946. */
  88947. function VirtualJoystick(leftJoystick) {
  88948. var _this = this;
  88949. if (leftJoystick) {
  88950. this._leftJoystick = true;
  88951. }
  88952. else {
  88953. this._leftJoystick = false;
  88954. }
  88955. VirtualJoystick._globalJoystickIndex++;
  88956. // By default left & right arrow keys are moving the X
  88957. // and up & down keys are moving the Y
  88958. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88959. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88960. this.reverseLeftRight = false;
  88961. this.reverseUpDown = false;
  88962. // collections of pointers
  88963. this._touches = new BABYLON.StringDictionary();
  88964. this.deltaPosition = BABYLON.Vector3.Zero();
  88965. this._joystickSensibility = 25;
  88966. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88967. this._onResize = function (evt) {
  88968. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88969. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88970. if (VirtualJoystick.vjCanvas) {
  88971. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88972. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88973. }
  88974. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88975. };
  88976. // injecting a canvas element on top of the canvas 3D game
  88977. if (!VirtualJoystick.vjCanvas) {
  88978. window.addEventListener("resize", this._onResize, false);
  88979. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88980. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88981. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88982. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88983. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88984. VirtualJoystick.vjCanvas.style.width = "100%";
  88985. VirtualJoystick.vjCanvas.style.height = "100%";
  88986. VirtualJoystick.vjCanvas.style.position = "absolute";
  88987. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88988. VirtualJoystick.vjCanvas.style.top = "0px";
  88989. VirtualJoystick.vjCanvas.style.left = "0px";
  88990. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88991. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88992. // Support for jQuery PEP polyfill
  88993. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88994. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88995. if (!context) {
  88996. throw new Error("Unable to create canvas for virtual joystick");
  88997. }
  88998. VirtualJoystick.vjCanvasContext = context;
  88999. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89000. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89001. document.body.appendChild(VirtualJoystick.vjCanvas);
  89002. }
  89003. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89004. this.pressed = false;
  89005. // default joystick color
  89006. this._joystickColor = "cyan";
  89007. this._joystickPointerID = -1;
  89008. // current joystick position
  89009. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89010. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89011. // origin joystick position
  89012. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89013. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89014. this._onPointerDownHandlerRef = function (evt) {
  89015. _this._onPointerDown(evt);
  89016. };
  89017. this._onPointerMoveHandlerRef = function (evt) {
  89018. _this._onPointerMove(evt);
  89019. };
  89020. this._onPointerUpHandlerRef = function (evt) {
  89021. _this._onPointerUp(evt);
  89022. };
  89023. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89024. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89025. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89026. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89027. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89028. evt.preventDefault(); // Disables system menu
  89029. }, false);
  89030. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89031. }
  89032. /**
  89033. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89034. * @param newJoystickSensibility defines the new sensibility
  89035. */
  89036. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89037. this._joystickSensibility = newJoystickSensibility;
  89038. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89039. };
  89040. VirtualJoystick.prototype._onPointerDown = function (e) {
  89041. var positionOnScreenCondition;
  89042. e.preventDefault();
  89043. if (this._leftJoystick === true) {
  89044. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89045. }
  89046. else {
  89047. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89048. }
  89049. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89050. // First contact will be dedicated to the virtual joystick
  89051. this._joystickPointerID = e.pointerId;
  89052. this._joystickPointerStartPos.x = e.clientX;
  89053. this._joystickPointerStartPos.y = e.clientY;
  89054. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89055. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89056. this._deltaJoystickVector.x = 0;
  89057. this._deltaJoystickVector.y = 0;
  89058. this.pressed = true;
  89059. this._touches.add(e.pointerId.toString(), e);
  89060. }
  89061. else {
  89062. // You can only trigger the action buttons with a joystick declared
  89063. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89064. this._action();
  89065. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89066. }
  89067. }
  89068. };
  89069. VirtualJoystick.prototype._onPointerMove = function (e) {
  89070. // If the current pointer is the one associated to the joystick (first touch contact)
  89071. if (this._joystickPointerID == e.pointerId) {
  89072. this._joystickPointerPos.x = e.clientX;
  89073. this._joystickPointerPos.y = e.clientY;
  89074. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89075. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89076. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89077. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89078. switch (this._axisTargetedByLeftAndRight) {
  89079. case JoystickAxis.X:
  89080. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89081. break;
  89082. case JoystickAxis.Y:
  89083. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89084. break;
  89085. case JoystickAxis.Z:
  89086. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89087. break;
  89088. }
  89089. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89090. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89091. switch (this._axisTargetedByUpAndDown) {
  89092. case JoystickAxis.X:
  89093. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89094. break;
  89095. case JoystickAxis.Y:
  89096. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89097. break;
  89098. case JoystickAxis.Z:
  89099. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89100. break;
  89101. }
  89102. }
  89103. else {
  89104. var data = this._touches.get(e.pointerId.toString());
  89105. if (data) {
  89106. data.x = e.clientX;
  89107. data.y = e.clientY;
  89108. }
  89109. }
  89110. };
  89111. VirtualJoystick.prototype._onPointerUp = function (e) {
  89112. if (this._joystickPointerID == e.pointerId) {
  89113. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89114. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89115. this._joystickPointerID = -1;
  89116. this.pressed = false;
  89117. }
  89118. else {
  89119. var touch = this._touches.get(e.pointerId.toString());
  89120. if (touch) {
  89121. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89122. }
  89123. }
  89124. this._deltaJoystickVector.x = 0;
  89125. this._deltaJoystickVector.y = 0;
  89126. this._touches.remove(e.pointerId.toString());
  89127. };
  89128. /**
  89129. * Change the color of the virtual joystick
  89130. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89131. */
  89132. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89133. this._joystickColor = newColor;
  89134. };
  89135. /**
  89136. * Defines a callback to call when the joystick is touched
  89137. * @param action defines the callback
  89138. */
  89139. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89140. this._action = action;
  89141. };
  89142. /**
  89143. * Defines which axis you'd like to control for left & right
  89144. * @param axis defines the axis to use
  89145. */
  89146. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89147. switch (axis) {
  89148. case JoystickAxis.X:
  89149. case JoystickAxis.Y:
  89150. case JoystickAxis.Z:
  89151. this._axisTargetedByLeftAndRight = axis;
  89152. break;
  89153. default:
  89154. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89155. break;
  89156. }
  89157. };
  89158. /**
  89159. * Defines which axis you'd like to control for up & down
  89160. * @param axis defines the axis to use
  89161. */
  89162. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89163. switch (axis) {
  89164. case JoystickAxis.X:
  89165. case JoystickAxis.Y:
  89166. case JoystickAxis.Z:
  89167. this._axisTargetedByUpAndDown = axis;
  89168. break;
  89169. default:
  89170. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89171. break;
  89172. }
  89173. };
  89174. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89175. var _this = this;
  89176. if (this.pressed) {
  89177. this._touches.forEach(function (key, touch) {
  89178. if (touch.pointerId === _this._joystickPointerID) {
  89179. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89180. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89181. VirtualJoystick.vjCanvasContext.beginPath();
  89182. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89183. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89184. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89185. VirtualJoystick.vjCanvasContext.stroke();
  89186. VirtualJoystick.vjCanvasContext.closePath();
  89187. VirtualJoystick.vjCanvasContext.beginPath();
  89188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89189. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89190. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89191. VirtualJoystick.vjCanvasContext.stroke();
  89192. VirtualJoystick.vjCanvasContext.closePath();
  89193. VirtualJoystick.vjCanvasContext.beginPath();
  89194. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89195. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89196. VirtualJoystick.vjCanvasContext.stroke();
  89197. VirtualJoystick.vjCanvasContext.closePath();
  89198. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89199. }
  89200. else {
  89201. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89202. VirtualJoystick.vjCanvasContext.beginPath();
  89203. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89204. VirtualJoystick.vjCanvasContext.beginPath();
  89205. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89206. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89207. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89208. VirtualJoystick.vjCanvasContext.stroke();
  89209. VirtualJoystick.vjCanvasContext.closePath();
  89210. touch.prevX = touch.x;
  89211. touch.prevY = touch.y;
  89212. }
  89213. ;
  89214. });
  89215. }
  89216. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89217. };
  89218. /**
  89219. * Release internal HTML canvas
  89220. */
  89221. VirtualJoystick.prototype.releaseCanvas = function () {
  89222. if (VirtualJoystick.vjCanvas) {
  89223. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89224. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89225. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89226. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89227. window.removeEventListener("resize", this._onResize);
  89228. document.body.removeChild(VirtualJoystick.vjCanvas);
  89229. VirtualJoystick.vjCanvas = null;
  89230. }
  89231. };
  89232. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89233. VirtualJoystick._globalJoystickIndex = 0;
  89234. return VirtualJoystick;
  89235. }());
  89236. BABYLON.VirtualJoystick = VirtualJoystick;
  89237. })(BABYLON || (BABYLON = {}));
  89238. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89239. var BABYLON;
  89240. (function (BABYLON) {
  89241. // We're mainly based on the logic defined into the FreeCamera code
  89242. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89243. __extends(VirtualJoysticksCamera, _super);
  89244. function VirtualJoysticksCamera(name, position, scene) {
  89245. var _this = _super.call(this, name, position, scene) || this;
  89246. _this.inputs.addVirtualJoystick();
  89247. return _this;
  89248. }
  89249. VirtualJoysticksCamera.prototype.getClassName = function () {
  89250. return "VirtualJoysticksCamera";
  89251. };
  89252. return VirtualJoysticksCamera;
  89253. }(BABYLON.FreeCamera));
  89254. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89255. })(BABYLON || (BABYLON = {}));
  89256. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89257. var BABYLON;
  89258. (function (BABYLON) {
  89259. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89260. function FreeCameraVirtualJoystickInput() {
  89261. }
  89262. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89263. return this._leftjoystick;
  89264. };
  89265. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89266. return this._rightjoystick;
  89267. };
  89268. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89269. if (this._leftjoystick) {
  89270. var camera = this.camera;
  89271. var speed = camera._computeLocalCameraSpeed() * 50;
  89272. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89273. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89274. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89275. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89276. if (!this._leftjoystick.pressed) {
  89277. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89278. }
  89279. if (!this._rightjoystick.pressed) {
  89280. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89281. }
  89282. }
  89283. };
  89284. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89285. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89286. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89287. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89288. this._leftjoystick.setJoystickSensibility(0.15);
  89289. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89290. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89291. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89292. this._rightjoystick.reverseUpDown = true;
  89293. this._rightjoystick.setJoystickSensibility(0.05);
  89294. this._rightjoystick.setJoystickColor("yellow");
  89295. };
  89296. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89297. this._leftjoystick.releaseCanvas();
  89298. this._rightjoystick.releaseCanvas();
  89299. };
  89300. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89301. return "FreeCameraVirtualJoystickInput";
  89302. };
  89303. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89304. return "virtualJoystick";
  89305. };
  89306. return FreeCameraVirtualJoystickInput;
  89307. }());
  89308. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89309. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89310. })(BABYLON || (BABYLON = {}));
  89311. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89312. var BABYLON;
  89313. (function (BABYLON) {
  89314. var SimplificationSettings = /** @class */ (function () {
  89315. function SimplificationSettings(quality, distance, optimizeMesh) {
  89316. this.quality = quality;
  89317. this.distance = distance;
  89318. this.optimizeMesh = optimizeMesh;
  89319. }
  89320. return SimplificationSettings;
  89321. }());
  89322. BABYLON.SimplificationSettings = SimplificationSettings;
  89323. var SimplificationQueue = /** @class */ (function () {
  89324. function SimplificationQueue() {
  89325. this.running = false;
  89326. this._simplificationArray = [];
  89327. }
  89328. SimplificationQueue.prototype.addTask = function (task) {
  89329. this._simplificationArray.push(task);
  89330. };
  89331. SimplificationQueue.prototype.executeNext = function () {
  89332. var task = this._simplificationArray.pop();
  89333. if (task) {
  89334. this.running = true;
  89335. this.runSimplification(task);
  89336. }
  89337. else {
  89338. this.running = false;
  89339. }
  89340. };
  89341. SimplificationQueue.prototype.runSimplification = function (task) {
  89342. var _this = this;
  89343. if (task.parallelProcessing) {
  89344. //parallel simplifier
  89345. task.settings.forEach(function (setting) {
  89346. var simplifier = _this.getSimplifier(task);
  89347. simplifier.simplify(setting, function (newMesh) {
  89348. task.mesh.addLODLevel(setting.distance, newMesh);
  89349. newMesh.isVisible = true;
  89350. //check if it is the last
  89351. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89352. //all done, run the success callback.
  89353. task.successCallback();
  89354. }
  89355. _this.executeNext();
  89356. });
  89357. });
  89358. }
  89359. else {
  89360. //single simplifier.
  89361. var simplifier = this.getSimplifier(task);
  89362. var runDecimation = function (setting, callback) {
  89363. simplifier.simplify(setting, function (newMesh) {
  89364. task.mesh.addLODLevel(setting.distance, newMesh);
  89365. newMesh.isVisible = true;
  89366. //run the next quality level
  89367. callback();
  89368. });
  89369. };
  89370. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89371. runDecimation(task.settings[loop.index], function () {
  89372. loop.executeNext();
  89373. });
  89374. }, function () {
  89375. //execution ended, run the success callback.
  89376. if (task.successCallback) {
  89377. task.successCallback();
  89378. }
  89379. _this.executeNext();
  89380. });
  89381. }
  89382. };
  89383. SimplificationQueue.prototype.getSimplifier = function (task) {
  89384. switch (task.simplificationType) {
  89385. case SimplificationType.QUADRATIC:
  89386. default:
  89387. return new QuadraticErrorSimplification(task.mesh);
  89388. }
  89389. };
  89390. return SimplificationQueue;
  89391. }());
  89392. BABYLON.SimplificationQueue = SimplificationQueue;
  89393. /**
  89394. * The implemented types of simplification
  89395. * At the moment only Quadratic Error Decimation is implemented
  89396. */
  89397. var SimplificationType;
  89398. (function (SimplificationType) {
  89399. /** Quadratic error decimation */
  89400. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89401. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89402. var DecimationTriangle = /** @class */ (function () {
  89403. function DecimationTriangle(vertices) {
  89404. this.vertices = vertices;
  89405. this.error = new Array(4);
  89406. this.deleted = false;
  89407. this.isDirty = false;
  89408. this.deletePending = false;
  89409. this.borderFactor = 0;
  89410. }
  89411. return DecimationTriangle;
  89412. }());
  89413. BABYLON.DecimationTriangle = DecimationTriangle;
  89414. var DecimationVertex = /** @class */ (function () {
  89415. function DecimationVertex(position, id) {
  89416. this.position = position;
  89417. this.id = id;
  89418. this.isBorder = true;
  89419. this.q = new QuadraticMatrix();
  89420. this.triangleCount = 0;
  89421. this.triangleStart = 0;
  89422. this.originalOffsets = [];
  89423. }
  89424. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89425. this.position.copyFrom(newPosition);
  89426. };
  89427. return DecimationVertex;
  89428. }());
  89429. BABYLON.DecimationVertex = DecimationVertex;
  89430. var QuadraticMatrix = /** @class */ (function () {
  89431. function QuadraticMatrix(data) {
  89432. this.data = new Array(10);
  89433. for (var i = 0; i < 10; ++i) {
  89434. if (data && data[i]) {
  89435. this.data[i] = data[i];
  89436. }
  89437. else {
  89438. this.data[i] = 0;
  89439. }
  89440. }
  89441. }
  89442. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89443. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89444. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89445. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89446. return det;
  89447. };
  89448. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89449. for (var i = 0; i < 10; ++i) {
  89450. this.data[i] += matrix.data[i];
  89451. }
  89452. };
  89453. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89454. for (var i = 0; i < 10; ++i) {
  89455. this.data[i] += data[i];
  89456. }
  89457. };
  89458. QuadraticMatrix.prototype.add = function (matrix) {
  89459. var m = new QuadraticMatrix();
  89460. for (var i = 0; i < 10; ++i) {
  89461. m.data[i] = this.data[i] + matrix.data[i];
  89462. }
  89463. return m;
  89464. };
  89465. QuadraticMatrix.FromData = function (a, b, c, d) {
  89466. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89467. };
  89468. //returning an array to avoid garbage collection
  89469. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89470. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89471. };
  89472. return QuadraticMatrix;
  89473. }());
  89474. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89475. var Reference = /** @class */ (function () {
  89476. function Reference(vertexId, triangleId) {
  89477. this.vertexId = vertexId;
  89478. this.triangleId = triangleId;
  89479. }
  89480. return Reference;
  89481. }());
  89482. BABYLON.Reference = Reference;
  89483. /**
  89484. * An implementation of the Quadratic Error simplification algorithm.
  89485. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89486. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89487. * @author RaananW
  89488. */
  89489. var QuadraticErrorSimplification = /** @class */ (function () {
  89490. function QuadraticErrorSimplification(_mesh) {
  89491. this._mesh = _mesh;
  89492. this.syncIterations = 5000;
  89493. this.aggressiveness = 7;
  89494. this.decimationIterations = 100;
  89495. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89496. }
  89497. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89498. var _this = this;
  89499. this.initDecimatedMesh();
  89500. //iterating through the submeshes array, one after the other.
  89501. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89502. _this.initWithMesh(loop.index, function () {
  89503. _this.runDecimation(settings, loop.index, function () {
  89504. loop.executeNext();
  89505. });
  89506. }, settings.optimizeMesh);
  89507. }, function () {
  89508. setTimeout(function () {
  89509. successCallback(_this._reconstructedMesh);
  89510. }, 0);
  89511. });
  89512. };
  89513. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89514. var _this = this;
  89515. var targetCount = ~~(this.triangles.length * settings.quality);
  89516. var deletedTriangles = 0;
  89517. var triangleCount = this.triangles.length;
  89518. var iterationFunction = function (iteration, callback) {
  89519. setTimeout(function () {
  89520. if (iteration % 5 === 0) {
  89521. _this.updateMesh(iteration === 0);
  89522. }
  89523. for (var i = 0; i < _this.triangles.length; ++i) {
  89524. _this.triangles[i].isDirty = false;
  89525. }
  89526. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89527. var trianglesIterator = function (i) {
  89528. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89529. var t = _this.triangles[tIdx];
  89530. if (!t)
  89531. return;
  89532. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89533. return;
  89534. }
  89535. for (var j = 0; j < 3; ++j) {
  89536. if (t.error[j] < threshold) {
  89537. var deleted0 = [];
  89538. var deleted1 = [];
  89539. var v0 = t.vertices[j];
  89540. var v1 = t.vertices[(j + 1) % 3];
  89541. if (v0.isBorder || v1.isBorder)
  89542. continue;
  89543. var p = BABYLON.Vector3.Zero();
  89544. var n = BABYLON.Vector3.Zero();
  89545. var uv = BABYLON.Vector2.Zero();
  89546. var color = new BABYLON.Color4(0, 0, 0, 1);
  89547. _this.calculateError(v0, v1, p, n, uv, color);
  89548. var delTr = new Array();
  89549. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89550. continue;
  89551. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89552. continue;
  89553. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89554. continue;
  89555. var uniqueArray = new Array();
  89556. delTr.forEach(function (deletedT) {
  89557. if (uniqueArray.indexOf(deletedT) === -1) {
  89558. deletedT.deletePending = true;
  89559. uniqueArray.push(deletedT);
  89560. }
  89561. });
  89562. if (uniqueArray.length % 2 !== 0) {
  89563. continue;
  89564. }
  89565. v0.q = v1.q.add(v0.q);
  89566. v0.updatePosition(p);
  89567. var tStart = _this.references.length;
  89568. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89569. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89570. var tCount = _this.references.length - tStart;
  89571. if (tCount <= v0.triangleCount) {
  89572. if (tCount) {
  89573. for (var c = 0; c < tCount; c++) {
  89574. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89575. }
  89576. }
  89577. }
  89578. else {
  89579. v0.triangleStart = tStart;
  89580. }
  89581. v0.triangleCount = tCount;
  89582. break;
  89583. }
  89584. }
  89585. };
  89586. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89587. }, 0);
  89588. };
  89589. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89590. if (triangleCount - deletedTriangles <= targetCount)
  89591. loop.breakLoop();
  89592. else {
  89593. iterationFunction(loop.index, function () {
  89594. loop.executeNext();
  89595. });
  89596. }
  89597. }, function () {
  89598. setTimeout(function () {
  89599. //reconstruct this part of the mesh
  89600. _this.reconstructMesh(submeshIndex);
  89601. successCallback();
  89602. }, 0);
  89603. });
  89604. };
  89605. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89606. var _this = this;
  89607. this.vertices = [];
  89608. this.triangles = [];
  89609. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89610. var indices = this._mesh.getIndices();
  89611. var submesh = this._mesh.subMeshes[submeshIndex];
  89612. var findInVertices = function (positionToSearch) {
  89613. if (optimizeMesh) {
  89614. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89615. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89616. return _this.vertices[ii];
  89617. }
  89618. }
  89619. }
  89620. return null;
  89621. };
  89622. var vertexReferences = [];
  89623. var vertexInit = function (i) {
  89624. if (!positionData) {
  89625. return;
  89626. }
  89627. var offset = i + submesh.verticesStart;
  89628. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89629. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89630. vertex.originalOffsets.push(offset);
  89631. if (vertex.id === _this.vertices.length) {
  89632. _this.vertices.push(vertex);
  89633. }
  89634. vertexReferences.push(vertex.id);
  89635. };
  89636. //var totalVertices = mesh.getTotalVertices();
  89637. var totalVertices = submesh.verticesCount;
  89638. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89639. var indicesInit = function (i) {
  89640. if (!indices) {
  89641. return;
  89642. }
  89643. var offset = (submesh.indexStart / 3) + i;
  89644. var pos = (offset * 3);
  89645. var i0 = indices[pos + 0];
  89646. var i1 = indices[pos + 1];
  89647. var i2 = indices[pos + 2];
  89648. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89649. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89650. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89651. var triangle = new DecimationTriangle([v0, v1, v2]);
  89652. triangle.originalOffset = pos;
  89653. _this.triangles.push(triangle);
  89654. };
  89655. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89656. _this.init(callback);
  89657. });
  89658. });
  89659. };
  89660. QuadraticErrorSimplification.prototype.init = function (callback) {
  89661. var _this = this;
  89662. var triangleInit1 = function (i) {
  89663. var t = _this.triangles[i];
  89664. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89665. for (var j = 0; j < 3; j++) {
  89666. 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))));
  89667. }
  89668. };
  89669. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89670. var triangleInit2 = function (i) {
  89671. var t = _this.triangles[i];
  89672. for (var j = 0; j < 3; ++j) {
  89673. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89674. }
  89675. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89676. };
  89677. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89678. callback();
  89679. });
  89680. });
  89681. };
  89682. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89683. var newTriangles = [];
  89684. var i;
  89685. for (i = 0; i < this.vertices.length; ++i) {
  89686. this.vertices[i].triangleCount = 0;
  89687. }
  89688. var t;
  89689. var j;
  89690. for (i = 0; i < this.triangles.length; ++i) {
  89691. if (!this.triangles[i].deleted) {
  89692. t = this.triangles[i];
  89693. for (j = 0; j < 3; ++j) {
  89694. t.vertices[j].triangleCount = 1;
  89695. }
  89696. newTriangles.push(t);
  89697. }
  89698. }
  89699. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89700. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89701. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89702. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89703. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89704. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89705. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89706. var vertexCount = 0;
  89707. for (i = 0; i < this.vertices.length; ++i) {
  89708. var vertex = this.vertices[i];
  89709. vertex.id = vertexCount;
  89710. if (vertex.triangleCount) {
  89711. vertex.originalOffsets.forEach(function (originalOffset) {
  89712. if (!normalData) {
  89713. return;
  89714. }
  89715. newPositionData.push(vertex.position.x);
  89716. newPositionData.push(vertex.position.y);
  89717. newPositionData.push(vertex.position.z);
  89718. newNormalData.push(normalData[originalOffset * 3]);
  89719. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89720. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89721. if (uvs && uvs.length) {
  89722. newUVsData.push(uvs[(originalOffset * 2)]);
  89723. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89724. }
  89725. else if (colorsData && colorsData.length) {
  89726. newColorsData.push(colorsData[(originalOffset * 4)]);
  89727. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89728. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89729. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89730. }
  89731. ++vertexCount;
  89732. });
  89733. }
  89734. }
  89735. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89736. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89737. var submeshesArray = this._reconstructedMesh.subMeshes;
  89738. this._reconstructedMesh.subMeshes = [];
  89739. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89740. var originalIndices = this._mesh.getIndices();
  89741. for (i = 0; i < newTriangles.length; ++i) {
  89742. t = newTriangles[i]; //now get the new referencing point for each vertex
  89743. [0, 1, 2].forEach(function (idx) {
  89744. var id = originalIndices[t.originalOffset + idx];
  89745. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89746. if (offset < 0)
  89747. offset = 0;
  89748. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89749. });
  89750. }
  89751. //overwriting the old vertex buffers and indices.
  89752. this._reconstructedMesh.setIndices(newIndicesArray);
  89753. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89754. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89755. if (newUVsData.length > 0)
  89756. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89757. if (newColorsData.length > 0)
  89758. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89759. //create submesh
  89760. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89761. if (submeshIndex > 0) {
  89762. this._reconstructedMesh.subMeshes = [];
  89763. submeshesArray.forEach(function (submesh) {
  89764. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89765. });
  89766. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89767. }
  89768. };
  89769. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89770. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89771. this._reconstructedMesh.material = this._mesh.material;
  89772. this._reconstructedMesh.parent = this._mesh.parent;
  89773. this._reconstructedMesh.isVisible = false;
  89774. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89775. };
  89776. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89777. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89778. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89779. if (t.deleted)
  89780. continue;
  89781. var s = this.references[vertex1.triangleStart + i].vertexId;
  89782. var v1 = t.vertices[(s + 1) % 3];
  89783. var v2 = t.vertices[(s + 2) % 3];
  89784. if ((v1 === vertex2 || v2 === vertex2)) {
  89785. deletedArray[i] = true;
  89786. delTr.push(t);
  89787. continue;
  89788. }
  89789. var d1 = v1.position.subtract(point);
  89790. d1 = d1.normalize();
  89791. var d2 = v2.position.subtract(point);
  89792. d2 = d2.normalize();
  89793. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89794. return true;
  89795. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89796. deletedArray[i] = false;
  89797. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89798. return true;
  89799. }
  89800. return false;
  89801. };
  89802. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89803. var newDeleted = deletedTriangles;
  89804. for (var i = 0; i < vertex.triangleCount; ++i) {
  89805. var ref = this.references[vertex.triangleStart + i];
  89806. var t = this.triangles[ref.triangleId];
  89807. if (t.deleted)
  89808. continue;
  89809. if (deletedArray[i] && t.deletePending) {
  89810. t.deleted = true;
  89811. newDeleted++;
  89812. continue;
  89813. }
  89814. t.vertices[ref.vertexId] = origVertex;
  89815. t.isDirty = true;
  89816. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89817. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89818. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89819. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89820. this.references.push(ref);
  89821. }
  89822. return newDeleted;
  89823. };
  89824. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89825. for (var i = 0; i < this.vertices.length; ++i) {
  89826. var vCount = [];
  89827. var vId = [];
  89828. var v = this.vertices[i];
  89829. var j;
  89830. for (j = 0; j < v.triangleCount; ++j) {
  89831. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89832. for (var ii = 0; ii < 3; ii++) {
  89833. var ofs = 0;
  89834. var vv = triangle.vertices[ii];
  89835. while (ofs < vCount.length) {
  89836. if (vId[ofs] === vv.id)
  89837. break;
  89838. ++ofs;
  89839. }
  89840. if (ofs === vCount.length) {
  89841. vCount.push(1);
  89842. vId.push(vv.id);
  89843. }
  89844. else {
  89845. vCount[ofs]++;
  89846. }
  89847. }
  89848. }
  89849. for (j = 0; j < vCount.length; ++j) {
  89850. if (vCount[j] === 1) {
  89851. this.vertices[vId[j]].isBorder = true;
  89852. }
  89853. else {
  89854. this.vertices[vId[j]].isBorder = false;
  89855. }
  89856. }
  89857. }
  89858. };
  89859. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89860. if (identifyBorders === void 0) { identifyBorders = false; }
  89861. var i;
  89862. if (!identifyBorders) {
  89863. var newTrianglesVector = [];
  89864. for (i = 0; i < this.triangles.length; ++i) {
  89865. if (!this.triangles[i].deleted) {
  89866. newTrianglesVector.push(this.triangles[i]);
  89867. }
  89868. }
  89869. this.triangles = newTrianglesVector;
  89870. }
  89871. for (i = 0; i < this.vertices.length; ++i) {
  89872. this.vertices[i].triangleCount = 0;
  89873. this.vertices[i].triangleStart = 0;
  89874. }
  89875. var t;
  89876. var j;
  89877. var v;
  89878. for (i = 0; i < this.triangles.length; ++i) {
  89879. t = this.triangles[i];
  89880. for (j = 0; j < 3; ++j) {
  89881. v = t.vertices[j];
  89882. v.triangleCount++;
  89883. }
  89884. }
  89885. var tStart = 0;
  89886. for (i = 0; i < this.vertices.length; ++i) {
  89887. this.vertices[i].triangleStart = tStart;
  89888. tStart += this.vertices[i].triangleCount;
  89889. this.vertices[i].triangleCount = 0;
  89890. }
  89891. var newReferences = new Array(this.triangles.length * 3);
  89892. for (i = 0; i < this.triangles.length; ++i) {
  89893. t = this.triangles[i];
  89894. for (j = 0; j < 3; ++j) {
  89895. v = t.vertices[j];
  89896. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89897. v.triangleCount++;
  89898. }
  89899. }
  89900. this.references = newReferences;
  89901. if (identifyBorders) {
  89902. this.identifyBorder();
  89903. }
  89904. };
  89905. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89906. var x = point.x;
  89907. var y = point.y;
  89908. var z = point.z;
  89909. 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
  89910. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89911. };
  89912. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89913. var q = vertex1.q.add(vertex2.q);
  89914. var border = vertex1.isBorder && vertex2.isBorder;
  89915. var error = 0;
  89916. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89917. if (qDet !== 0 && !border) {
  89918. if (!pointResult) {
  89919. pointResult = BABYLON.Vector3.Zero();
  89920. }
  89921. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89922. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89923. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89924. error = this.vertexError(q, pointResult);
  89925. }
  89926. else {
  89927. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89928. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89929. var error1 = this.vertexError(q, vertex1.position);
  89930. var error2 = this.vertexError(q, vertex2.position);
  89931. var error3 = this.vertexError(q, p3);
  89932. error = Math.min(error1, error2, error3);
  89933. if (error === error1) {
  89934. if (pointResult) {
  89935. pointResult.copyFrom(vertex1.position);
  89936. }
  89937. }
  89938. else if (error === error2) {
  89939. if (pointResult) {
  89940. pointResult.copyFrom(vertex2.position);
  89941. }
  89942. }
  89943. else {
  89944. if (pointResult) {
  89945. pointResult.copyFrom(p3);
  89946. }
  89947. }
  89948. }
  89949. return error;
  89950. };
  89951. return QuadraticErrorSimplification;
  89952. }());
  89953. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89954. })(BABYLON || (BABYLON = {}));
  89955. //# sourceMappingURL=babylon.meshSimplification.js.map
  89956. var BABYLON;
  89957. (function (BABYLON) {
  89958. var MeshLODLevel = /** @class */ (function () {
  89959. function MeshLODLevel(distance, mesh) {
  89960. this.distance = distance;
  89961. this.mesh = mesh;
  89962. }
  89963. return MeshLODLevel;
  89964. }());
  89965. BABYLON.MeshLODLevel = MeshLODLevel;
  89966. })(BABYLON || (BABYLON = {}));
  89967. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89968. var BABYLON;
  89969. (function (BABYLON) {
  89970. /**
  89971. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89972. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89973. */
  89974. var SceneOptimization = /** @class */ (function () {
  89975. /**
  89976. * Creates the SceneOptimization object
  89977. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89978. * @param desc defines the description associated with the optimization
  89979. */
  89980. function SceneOptimization(
  89981. /**
  89982. * Defines the priority of this optimization (0 by default which means first in the list)
  89983. */
  89984. priority) {
  89985. if (priority === void 0) { priority = 0; }
  89986. this.priority = priority;
  89987. }
  89988. /**
  89989. * Gets a string describing the action executed by the current optimization
  89990. * @returns description string
  89991. */
  89992. SceneOptimization.prototype.getDescription = function () {
  89993. return "";
  89994. };
  89995. /**
  89996. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89997. * @param scene defines the current scene where to apply this optimization
  89998. * @param optimizer defines the current optimizer
  89999. * @returns true if everything that can be done was applied
  90000. */
  90001. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90002. return true;
  90003. };
  90004. ;
  90005. return SceneOptimization;
  90006. }());
  90007. BABYLON.SceneOptimization = SceneOptimization;
  90008. /**
  90009. * Defines an optimization used to reduce the size of render target textures
  90010. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90011. */
  90012. var TextureOptimization = /** @class */ (function (_super) {
  90013. __extends(TextureOptimization, _super);
  90014. /**
  90015. * Creates the TextureOptimization object
  90016. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90017. * @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
  90018. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90019. */
  90020. function TextureOptimization(
  90021. /**
  90022. * Defines the priority of this optimization (0 by default which means first in the list)
  90023. */
  90024. priority,
  90025. /**
  90026. * 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
  90027. */
  90028. maximumSize,
  90029. /**
  90030. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90031. */
  90032. step) {
  90033. if (priority === void 0) { priority = 0; }
  90034. if (maximumSize === void 0) { maximumSize = 1024; }
  90035. if (step === void 0) { step = 0.5; }
  90036. var _this = _super.call(this, priority) || this;
  90037. _this.priority = priority;
  90038. _this.maximumSize = maximumSize;
  90039. _this.step = step;
  90040. return _this;
  90041. }
  90042. /**
  90043. * Gets a string describing the action executed by the current optimization
  90044. * @returns description string
  90045. */
  90046. TextureOptimization.prototype.getDescription = function () {
  90047. return "Reducing render target texture size to " + this.maximumSize;
  90048. };
  90049. /**
  90050. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90051. * @param scene defines the current scene where to apply this optimization
  90052. * @param optimizer defines the current optimizer
  90053. * @returns true if everything that can be done was applied
  90054. */
  90055. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90056. var allDone = true;
  90057. for (var index = 0; index < scene.textures.length; index++) {
  90058. var texture = scene.textures[index];
  90059. if (!texture.canRescale || texture.getContext) {
  90060. continue;
  90061. }
  90062. var currentSize = texture.getSize();
  90063. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90064. if (maxDimension > this.maximumSize) {
  90065. texture.scale(this.step);
  90066. allDone = false;
  90067. }
  90068. }
  90069. return allDone;
  90070. };
  90071. return TextureOptimization;
  90072. }(SceneOptimization));
  90073. BABYLON.TextureOptimization = TextureOptimization;
  90074. /**
  90075. * Defines an optimization used to increase or decrease the rendering resolution
  90076. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90077. */
  90078. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90079. __extends(HardwareScalingOptimization, _super);
  90080. /**
  90081. * Creates the HardwareScalingOptimization object
  90082. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90083. * @param maximumScale defines the maximum scale to use (2 by default)
  90084. * @param step defines the step to use between two passes (0.5 by default)
  90085. */
  90086. function HardwareScalingOptimization(
  90087. /**
  90088. * Defines the priority of this optimization (0 by default which means first in the list)
  90089. */
  90090. priority,
  90091. /**
  90092. * Defines the maximum scale to use (2 by default)
  90093. */
  90094. maximumScale,
  90095. /**
  90096. * Defines the step to use between two passes (0.5 by default)
  90097. */
  90098. step) {
  90099. if (priority === void 0) { priority = 0; }
  90100. if (maximumScale === void 0) { maximumScale = 2; }
  90101. if (step === void 0) { step = 0.25; }
  90102. var _this = _super.call(this, priority) || this;
  90103. _this.priority = priority;
  90104. _this.maximumScale = maximumScale;
  90105. _this.step = step;
  90106. _this._currentScale = -1;
  90107. _this._directionOffset = 1;
  90108. return _this;
  90109. }
  90110. /**
  90111. * Gets a string describing the action executed by the current optimization
  90112. * @return description string
  90113. */
  90114. HardwareScalingOptimization.prototype.getDescription = function () {
  90115. return "Setting hardware scaling level to " + this._currentScale;
  90116. };
  90117. /**
  90118. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90119. * @param scene defines the current scene where to apply this optimization
  90120. * @param optimizer defines the current optimizer
  90121. * @returns true if everything that can be done was applied
  90122. */
  90123. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90124. if (this._currentScale === -1) {
  90125. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90126. if (this._currentScale > this.maximumScale) {
  90127. this._directionOffset = -1;
  90128. }
  90129. }
  90130. this._currentScale += this._directionOffset * this.step;
  90131. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90132. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90133. };
  90134. ;
  90135. return HardwareScalingOptimization;
  90136. }(SceneOptimization));
  90137. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90138. /**
  90139. * Defines an optimization used to remove shadows
  90140. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90141. */
  90142. var ShadowsOptimization = /** @class */ (function (_super) {
  90143. __extends(ShadowsOptimization, _super);
  90144. function ShadowsOptimization() {
  90145. return _super !== null && _super.apply(this, arguments) || this;
  90146. }
  90147. /**
  90148. * Gets a string describing the action executed by the current optimization
  90149. * @return description string
  90150. */
  90151. ShadowsOptimization.prototype.getDescription = function () {
  90152. return "Turning shadows on/off";
  90153. };
  90154. /**
  90155. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90156. * @param scene defines the current scene where to apply this optimization
  90157. * @param optimizer defines the current optimizer
  90158. * @returns true if everything that can be done was applied
  90159. */
  90160. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90161. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90162. return true;
  90163. };
  90164. ;
  90165. return ShadowsOptimization;
  90166. }(SceneOptimization));
  90167. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90168. /**
  90169. * Defines an optimization used to turn post-processes off
  90170. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90171. */
  90172. var PostProcessesOptimization = /** @class */ (function (_super) {
  90173. __extends(PostProcessesOptimization, _super);
  90174. function PostProcessesOptimization() {
  90175. return _super !== null && _super.apply(this, arguments) || this;
  90176. }
  90177. /**
  90178. * Gets a string describing the action executed by the current optimization
  90179. * @return description string
  90180. */
  90181. PostProcessesOptimization.prototype.getDescription = function () {
  90182. return "Turning post-processes on/off";
  90183. };
  90184. /**
  90185. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90186. * @param scene defines the current scene where to apply this optimization
  90187. * @param optimizer defines the current optimizer
  90188. * @returns true if everything that can be done was applied
  90189. */
  90190. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90191. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90192. return true;
  90193. };
  90194. ;
  90195. return PostProcessesOptimization;
  90196. }(SceneOptimization));
  90197. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90198. /**
  90199. * Defines an optimization used to turn lens flares off
  90200. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90201. */
  90202. var LensFlaresOptimization = /** @class */ (function (_super) {
  90203. __extends(LensFlaresOptimization, _super);
  90204. function LensFlaresOptimization() {
  90205. return _super !== null && _super.apply(this, arguments) || this;
  90206. }
  90207. /**
  90208. * Gets a string describing the action executed by the current optimization
  90209. * @return description string
  90210. */
  90211. LensFlaresOptimization.prototype.getDescription = function () {
  90212. return "Turning lens flares on/off";
  90213. };
  90214. /**
  90215. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90216. * @param scene defines the current scene where to apply this optimization
  90217. * @param optimizer defines the current optimizer
  90218. * @returns true if everything that can be done was applied
  90219. */
  90220. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90221. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90222. return true;
  90223. };
  90224. ;
  90225. return LensFlaresOptimization;
  90226. }(SceneOptimization));
  90227. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90228. /**
  90229. * Defines an optimization based on user defined callback.
  90230. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90231. */
  90232. var CustomOptimization = /** @class */ (function (_super) {
  90233. __extends(CustomOptimization, _super);
  90234. function CustomOptimization() {
  90235. return _super !== null && _super.apply(this, arguments) || this;
  90236. }
  90237. /**
  90238. * Gets a string describing the action executed by the current optimization
  90239. * @returns description string
  90240. */
  90241. CustomOptimization.prototype.getDescription = function () {
  90242. if (this.onGetDescription) {
  90243. return this.onGetDescription();
  90244. }
  90245. return "Running user defined callback";
  90246. };
  90247. /**
  90248. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90249. * @param scene defines the current scene where to apply this optimization
  90250. * @param optimizer defines the current optimizer
  90251. * @returns true if everything that can be done was applied
  90252. */
  90253. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90254. if (this.onApply) {
  90255. return this.onApply(scene, optimizer);
  90256. }
  90257. return true;
  90258. };
  90259. ;
  90260. return CustomOptimization;
  90261. }(SceneOptimization));
  90262. BABYLON.CustomOptimization = CustomOptimization;
  90263. /**
  90264. * Defines an optimization used to turn particles off
  90265. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90266. */
  90267. var ParticlesOptimization = /** @class */ (function (_super) {
  90268. __extends(ParticlesOptimization, _super);
  90269. function ParticlesOptimization() {
  90270. return _super !== null && _super.apply(this, arguments) || this;
  90271. }
  90272. /**
  90273. * Gets a string describing the action executed by the current optimization
  90274. * @return description string
  90275. */
  90276. ParticlesOptimization.prototype.getDescription = function () {
  90277. return "Turning particles on/off";
  90278. };
  90279. /**
  90280. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90281. * @param scene defines the current scene where to apply this optimization
  90282. * @param optimizer defines the current optimizer
  90283. * @returns true if everything that can be done was applied
  90284. */
  90285. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90286. scene.particlesEnabled = optimizer.isInImprovementMode;
  90287. return true;
  90288. };
  90289. ;
  90290. return ParticlesOptimization;
  90291. }(SceneOptimization));
  90292. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90293. /**
  90294. * Defines an optimization used to turn render targets off
  90295. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90296. */
  90297. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90298. __extends(RenderTargetsOptimization, _super);
  90299. function RenderTargetsOptimization() {
  90300. return _super !== null && _super.apply(this, arguments) || this;
  90301. }
  90302. /**
  90303. * Gets a string describing the action executed by the current optimization
  90304. * @return description string
  90305. */
  90306. RenderTargetsOptimization.prototype.getDescription = function () {
  90307. return "Turning render targets off";
  90308. };
  90309. /**
  90310. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90311. * @param scene defines the current scene where to apply this optimization
  90312. * @param optimizer defines the current optimizer
  90313. * @returns true if everything that can be done was applied
  90314. */
  90315. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90316. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90317. return true;
  90318. };
  90319. ;
  90320. return RenderTargetsOptimization;
  90321. }(SceneOptimization));
  90322. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90323. /**
  90324. * Defines an optimization used to merge meshes with compatible materials
  90325. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90326. */
  90327. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90328. __extends(MergeMeshesOptimization, _super);
  90329. function MergeMeshesOptimization() {
  90330. var _this = _super !== null && _super.apply(this, arguments) || this;
  90331. _this._canBeMerged = function (abstractMesh) {
  90332. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90333. return false;
  90334. }
  90335. var mesh = abstractMesh;
  90336. if (!mesh.isVisible || !mesh.isEnabled()) {
  90337. return false;
  90338. }
  90339. if (mesh.instances.length > 0) {
  90340. return false;
  90341. }
  90342. if (mesh.skeleton || mesh.hasLODLevels) {
  90343. return false;
  90344. }
  90345. if (mesh.parent) {
  90346. return false;
  90347. }
  90348. return true;
  90349. };
  90350. return _this;
  90351. }
  90352. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90353. /**
  90354. * Gets or sets a boolean which defines if optimization octree has to be updated
  90355. */
  90356. get: function () {
  90357. return MergeMeshesOptimization._UpdateSelectionTree;
  90358. },
  90359. /**
  90360. * Gets or sets a boolean which defines if optimization octree has to be updated
  90361. */
  90362. set: function (value) {
  90363. MergeMeshesOptimization._UpdateSelectionTree = value;
  90364. },
  90365. enumerable: true,
  90366. configurable: true
  90367. });
  90368. /**
  90369. * Gets a string describing the action executed by the current optimization
  90370. * @return description string
  90371. */
  90372. MergeMeshesOptimization.prototype.getDescription = function () {
  90373. return "Merging similar meshes together";
  90374. };
  90375. /**
  90376. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90377. * @param scene defines the current scene where to apply this optimization
  90378. * @param optimizer defines the current optimizer
  90379. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90380. * @returns true if everything that can be done was applied
  90381. */
  90382. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90383. var globalPool = scene.meshes.slice(0);
  90384. var globalLength = globalPool.length;
  90385. for (var index = 0; index < globalLength; index++) {
  90386. var currentPool = new Array();
  90387. var current = globalPool[index];
  90388. // Checks
  90389. if (!this._canBeMerged(current)) {
  90390. continue;
  90391. }
  90392. currentPool.push(current);
  90393. // Find compatible meshes
  90394. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90395. var otherMesh = globalPool[subIndex];
  90396. if (!this._canBeMerged(otherMesh)) {
  90397. continue;
  90398. }
  90399. if (otherMesh.material !== current.material) {
  90400. continue;
  90401. }
  90402. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90403. continue;
  90404. }
  90405. currentPool.push(otherMesh);
  90406. globalLength--;
  90407. globalPool.splice(subIndex, 1);
  90408. subIndex--;
  90409. }
  90410. if (currentPool.length < 2) {
  90411. continue;
  90412. }
  90413. // Merge meshes
  90414. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90415. }
  90416. if (updateSelectionTree != undefined) {
  90417. if (updateSelectionTree) {
  90418. scene.createOrUpdateSelectionOctree();
  90419. }
  90420. }
  90421. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90422. scene.createOrUpdateSelectionOctree();
  90423. }
  90424. return true;
  90425. };
  90426. ;
  90427. MergeMeshesOptimization._UpdateSelectionTree = false;
  90428. return MergeMeshesOptimization;
  90429. }(SceneOptimization));
  90430. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90431. /**
  90432. * Defines a list of options used by SceneOptimizer
  90433. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90434. */
  90435. var SceneOptimizerOptions = /** @class */ (function () {
  90436. /**
  90437. * Creates a new list of options used by SceneOptimizer
  90438. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90439. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90440. */
  90441. function SceneOptimizerOptions(
  90442. /**
  90443. * Defines the target frame rate to reach (60 by default)
  90444. */
  90445. targetFrameRate,
  90446. /**
  90447. * Defines the interval between two checkes (2000ms by default)
  90448. */
  90449. trackerDuration) {
  90450. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90451. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90452. this.targetFrameRate = targetFrameRate;
  90453. this.trackerDuration = trackerDuration;
  90454. /**
  90455. * Gets the list of optimizations to apply
  90456. */
  90457. this.optimizations = new Array();
  90458. }
  90459. /**
  90460. * Add a new optimization
  90461. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90462. * @returns the current SceneOptimizerOptions
  90463. */
  90464. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90465. this.optimizations.push(optimization);
  90466. return this;
  90467. };
  90468. /**
  90469. * Add a new custom optimization
  90470. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90471. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90472. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90473. * @returns the current SceneOptimizerOptions
  90474. */
  90475. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90476. if (priority === void 0) { priority = 0; }
  90477. var optimization = new CustomOptimization(priority);
  90478. optimization.onApply = onApply;
  90479. optimization.onGetDescription = onGetDescription;
  90480. this.optimizations.push(optimization);
  90481. return this;
  90482. };
  90483. /**
  90484. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90485. * @param targetFrameRate defines the target frame rate (60 by default)
  90486. * @returns a SceneOptimizerOptions object
  90487. */
  90488. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90489. var result = new SceneOptimizerOptions(targetFrameRate);
  90490. var priority = 0;
  90491. result.addOptimization(new MergeMeshesOptimization(priority));
  90492. result.addOptimization(new ShadowsOptimization(priority));
  90493. result.addOptimization(new LensFlaresOptimization(priority));
  90494. // Next priority
  90495. priority++;
  90496. result.addOptimization(new PostProcessesOptimization(priority));
  90497. result.addOptimization(new ParticlesOptimization(priority));
  90498. // Next priority
  90499. priority++;
  90500. result.addOptimization(new TextureOptimization(priority, 1024));
  90501. return result;
  90502. };
  90503. /**
  90504. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90505. * @param targetFrameRate defines the target frame rate (60 by default)
  90506. * @returns a SceneOptimizerOptions object
  90507. */
  90508. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90509. var result = new SceneOptimizerOptions(targetFrameRate);
  90510. var priority = 0;
  90511. result.addOptimization(new MergeMeshesOptimization(priority));
  90512. result.addOptimization(new ShadowsOptimization(priority));
  90513. result.addOptimization(new LensFlaresOptimization(priority));
  90514. // Next priority
  90515. priority++;
  90516. result.addOptimization(new PostProcessesOptimization(priority));
  90517. result.addOptimization(new ParticlesOptimization(priority));
  90518. // Next priority
  90519. priority++;
  90520. result.addOptimization(new TextureOptimization(priority, 512));
  90521. // Next priority
  90522. priority++;
  90523. result.addOptimization(new RenderTargetsOptimization(priority));
  90524. // Next priority
  90525. priority++;
  90526. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90527. return result;
  90528. };
  90529. /**
  90530. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90531. * @param targetFrameRate defines the target frame rate (60 by default)
  90532. * @returns a SceneOptimizerOptions object
  90533. */
  90534. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90535. var result = new SceneOptimizerOptions(targetFrameRate);
  90536. var priority = 0;
  90537. result.addOptimization(new MergeMeshesOptimization(priority));
  90538. result.addOptimization(new ShadowsOptimization(priority));
  90539. result.addOptimization(new LensFlaresOptimization(priority));
  90540. // Next priority
  90541. priority++;
  90542. result.addOptimization(new PostProcessesOptimization(priority));
  90543. result.addOptimization(new ParticlesOptimization(priority));
  90544. // Next priority
  90545. priority++;
  90546. result.addOptimization(new TextureOptimization(priority, 256));
  90547. // Next priority
  90548. priority++;
  90549. result.addOptimization(new RenderTargetsOptimization(priority));
  90550. // Next priority
  90551. priority++;
  90552. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90553. return result;
  90554. };
  90555. return SceneOptimizerOptions;
  90556. }());
  90557. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90558. /**
  90559. * Class used to run optimizations in order to reach a target frame rate
  90560. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90561. */
  90562. var SceneOptimizer = /** @class */ (function () {
  90563. /**
  90564. * Creates a new SceneOptimizer
  90565. * @param scene defines the scene to work on
  90566. * @param options defines the options to use with the SceneOptimizer
  90567. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90568. * @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)
  90569. */
  90570. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90571. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90572. if (improvementMode === void 0) { improvementMode = false; }
  90573. var _this = this;
  90574. this._isRunning = false;
  90575. this._currentPriorityLevel = 0;
  90576. this._targetFrameRate = 60;
  90577. this._trackerDuration = 2000;
  90578. this._currentFrameRate = 0;
  90579. this._improvementMode = false;
  90580. /**
  90581. * Defines an observable called when the optimizer reaches the target frame rate
  90582. */
  90583. this.onSuccessObservable = new BABYLON.Observable();
  90584. /**
  90585. * Defines an observable called when the optimizer enables an optimization
  90586. */
  90587. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90588. /**
  90589. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90590. */
  90591. this.onFailureObservable = new BABYLON.Observable();
  90592. if (!options) {
  90593. this._options = new SceneOptimizerOptions();
  90594. }
  90595. else {
  90596. this._options = options;
  90597. }
  90598. if (this._options.targetFrameRate) {
  90599. this._targetFrameRate = this._options.targetFrameRate;
  90600. }
  90601. if (this._options.trackerDuration) {
  90602. this._trackerDuration = this._options.trackerDuration;
  90603. }
  90604. if (autoGeneratePriorities) {
  90605. var priority = 0;
  90606. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90607. var optim = _a[_i];
  90608. optim.priority = priority++;
  90609. }
  90610. }
  90611. this._improvementMode = improvementMode;
  90612. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90613. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90614. _this._sceneDisposeObserver = null;
  90615. _this.dispose();
  90616. });
  90617. }
  90618. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90619. /**
  90620. * Gets a boolean indicating if the optimizer is in improvement mode
  90621. */
  90622. get: function () {
  90623. return this._improvementMode;
  90624. },
  90625. enumerable: true,
  90626. configurable: true
  90627. });
  90628. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90629. /**
  90630. * Gets the current priority level (0 at start)
  90631. */
  90632. get: function () {
  90633. return this._currentPriorityLevel;
  90634. },
  90635. enumerable: true,
  90636. configurable: true
  90637. });
  90638. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90639. /**
  90640. * Gets the current frame rate checked by the SceneOptimizer
  90641. */
  90642. get: function () {
  90643. return this._currentFrameRate;
  90644. },
  90645. enumerable: true,
  90646. configurable: true
  90647. });
  90648. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90649. /**
  90650. * Gets or sets the current target frame rate (60 by default)
  90651. */
  90652. get: function () {
  90653. return this._targetFrameRate;
  90654. },
  90655. /**
  90656. * Gets or sets the current target frame rate (60 by default)
  90657. */
  90658. set: function (value) {
  90659. this._targetFrameRate = value;
  90660. },
  90661. enumerable: true,
  90662. configurable: true
  90663. });
  90664. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90665. /**
  90666. * Gets or sets the current interval between two checks (every 2000ms by default)
  90667. */
  90668. get: function () {
  90669. return this._trackerDuration;
  90670. },
  90671. /**
  90672. * Gets or sets the current interval between two checks (every 2000ms by default)
  90673. */
  90674. set: function (value) {
  90675. this._trackerDuration = value;
  90676. },
  90677. enumerable: true,
  90678. configurable: true
  90679. });
  90680. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90681. /**
  90682. * Gets the list of active optimizations
  90683. */
  90684. get: function () {
  90685. return this._options.optimizations;
  90686. },
  90687. enumerable: true,
  90688. configurable: true
  90689. });
  90690. /**
  90691. * Stops the current optimizer
  90692. */
  90693. SceneOptimizer.prototype.stop = function () {
  90694. this._isRunning = false;
  90695. };
  90696. /**
  90697. * Reset the optimizer to initial step (current priority level = 0)
  90698. */
  90699. SceneOptimizer.prototype.reset = function () {
  90700. this._currentPriorityLevel = 0;
  90701. };
  90702. /**
  90703. * Start the optimizer. By default it will try to reach a specific framerate
  90704. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90705. */
  90706. SceneOptimizer.prototype.start = function () {
  90707. var _this = this;
  90708. if (this._isRunning) {
  90709. return;
  90710. }
  90711. this._isRunning = true;
  90712. // Let's wait for the scene to be ready before running our check
  90713. this._scene.executeWhenReady(function () {
  90714. setTimeout(function () {
  90715. _this._checkCurrentState();
  90716. }, _this._trackerDuration);
  90717. });
  90718. };
  90719. SceneOptimizer.prototype._checkCurrentState = function () {
  90720. var _this = this;
  90721. if (!this._isRunning) {
  90722. return;
  90723. }
  90724. var scene = this._scene;
  90725. var options = this._options;
  90726. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90727. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90728. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90729. this._isRunning = false;
  90730. this.onSuccessObservable.notifyObservers(this);
  90731. return;
  90732. }
  90733. // Apply current level of optimizations
  90734. var allDone = true;
  90735. var noOptimizationApplied = true;
  90736. for (var index = 0; index < options.optimizations.length; index++) {
  90737. var optimization = options.optimizations[index];
  90738. if (optimization.priority === this._currentPriorityLevel) {
  90739. noOptimizationApplied = false;
  90740. allDone = allDone && optimization.apply(scene, this);
  90741. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90742. }
  90743. }
  90744. // If no optimization was applied, this is a failure :(
  90745. if (noOptimizationApplied) {
  90746. this._isRunning = false;
  90747. this.onFailureObservable.notifyObservers(this);
  90748. return;
  90749. }
  90750. // If all optimizations were done, move to next level
  90751. if (allDone) {
  90752. this._currentPriorityLevel++;
  90753. }
  90754. // Let's the system running for a specific amount of time before checking FPS
  90755. scene.executeWhenReady(function () {
  90756. setTimeout(function () {
  90757. _this._checkCurrentState();
  90758. }, _this._trackerDuration);
  90759. });
  90760. };
  90761. /**
  90762. * Release all resources
  90763. */
  90764. SceneOptimizer.prototype.dispose = function () {
  90765. this.stop();
  90766. this.onSuccessObservable.clear();
  90767. this.onFailureObservable.clear();
  90768. this.onNewOptimizationAppliedObservable.clear();
  90769. if (this._sceneDisposeObserver) {
  90770. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90771. }
  90772. };
  90773. /**
  90774. * Helper function to create a SceneOptimizer with one single line of code
  90775. * @param scene defines the scene to work on
  90776. * @param options defines the options to use with the SceneOptimizer
  90777. * @param onSuccess defines a callback to call on success
  90778. * @param onFailure defines a callback to call on failure
  90779. * @returns the new SceneOptimizer object
  90780. */
  90781. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90782. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90783. if (onSuccess) {
  90784. optimizer.onSuccessObservable.add(function () {
  90785. onSuccess();
  90786. });
  90787. }
  90788. if (onFailure) {
  90789. optimizer.onFailureObservable.add(function () {
  90790. onFailure();
  90791. });
  90792. }
  90793. optimizer.start();
  90794. return optimizer;
  90795. };
  90796. return SceneOptimizer;
  90797. }());
  90798. BABYLON.SceneOptimizer = SceneOptimizer;
  90799. })(BABYLON || (BABYLON = {}));
  90800. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90801. var BABYLON;
  90802. (function (BABYLON) {
  90803. var OutlineRenderer = /** @class */ (function () {
  90804. function OutlineRenderer(scene) {
  90805. this.zOffset = 1;
  90806. this._scene = scene;
  90807. }
  90808. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90809. var _this = this;
  90810. if (useOverlay === void 0) { useOverlay = false; }
  90811. var scene = this._scene;
  90812. var engine = this._scene.getEngine();
  90813. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90814. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90815. return;
  90816. }
  90817. var mesh = subMesh.getRenderingMesh();
  90818. var material = subMesh.getMaterial();
  90819. if (!material || !scene.activeCamera) {
  90820. return;
  90821. }
  90822. engine.enableEffect(this._effect);
  90823. // Logarithmic depth
  90824. if (material.useLogarithmicDepth) {
  90825. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90826. }
  90827. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90828. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90829. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90830. // Bones
  90831. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90832. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90833. }
  90834. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90835. // Alpha test
  90836. if (material && material.needAlphaTesting()) {
  90837. var alphaTexture = material.getAlphaTestTexture();
  90838. if (alphaTexture) {
  90839. this._effect.setTexture("diffuseSampler", alphaTexture);
  90840. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90841. }
  90842. }
  90843. engine.setZOffset(-this.zOffset);
  90844. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90845. engine.setZOffset(0);
  90846. };
  90847. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90848. var defines = [];
  90849. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90850. var mesh = subMesh.getMesh();
  90851. var material = subMesh.getMaterial();
  90852. if (material) {
  90853. // Alpha test
  90854. if (material.needAlphaTesting()) {
  90855. defines.push("#define ALPHATEST");
  90856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90857. attribs.push(BABYLON.VertexBuffer.UVKind);
  90858. defines.push("#define UV1");
  90859. }
  90860. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90861. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90862. defines.push("#define UV2");
  90863. }
  90864. }
  90865. //Logarithmic depth
  90866. if (material.useLogarithmicDepth) {
  90867. defines.push("#define LOGARITHMICDEPTH");
  90868. }
  90869. }
  90870. // Bones
  90871. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90874. if (mesh.numBoneInfluencers > 4) {
  90875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90877. }
  90878. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90879. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90880. }
  90881. else {
  90882. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90883. }
  90884. // Instances
  90885. if (useInstances) {
  90886. defines.push("#define INSTANCES");
  90887. attribs.push("world0");
  90888. attribs.push("world1");
  90889. attribs.push("world2");
  90890. attribs.push("world3");
  90891. }
  90892. // Get correct effect
  90893. var join = defines.join("\n");
  90894. if (this._cachedDefines !== join) {
  90895. this._cachedDefines = join;
  90896. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90897. }
  90898. return this._effect.isReady();
  90899. };
  90900. return OutlineRenderer;
  90901. }());
  90902. BABYLON.OutlineRenderer = OutlineRenderer;
  90903. })(BABYLON || (BABYLON = {}));
  90904. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90905. var BABYLON;
  90906. (function (BABYLON) {
  90907. var FaceAdjacencies = /** @class */ (function () {
  90908. function FaceAdjacencies() {
  90909. this.edges = new Array();
  90910. this.edgesConnectedCount = 0;
  90911. }
  90912. return FaceAdjacencies;
  90913. }());
  90914. var EdgesRenderer = /** @class */ (function () {
  90915. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90916. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90917. if (epsilon === void 0) { epsilon = 0.95; }
  90918. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90919. this.edgesWidthScalerForOrthographic = 1000.0;
  90920. this.edgesWidthScalerForPerspective = 50.0;
  90921. this._linesPositions = new Array();
  90922. this._linesNormals = new Array();
  90923. this._linesIndices = new Array();
  90924. this._buffers = {};
  90925. this._checkVerticesInsteadOfIndices = false;
  90926. this._source = source;
  90927. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90928. this._epsilon = epsilon;
  90929. this._prepareRessources();
  90930. this._generateEdgesLines();
  90931. }
  90932. EdgesRenderer.prototype._prepareRessources = function () {
  90933. if (this._lineShader) {
  90934. return;
  90935. }
  90936. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90937. attributes: ["position", "normal"],
  90938. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90939. });
  90940. this._lineShader.disableDepthWrite = true;
  90941. this._lineShader.backFaceCulling = false;
  90942. };
  90943. EdgesRenderer.prototype._rebuild = function () {
  90944. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90945. if (buffer) {
  90946. buffer._rebuild();
  90947. }
  90948. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90949. if (buffer) {
  90950. buffer._rebuild();
  90951. }
  90952. var scene = this._source.getScene();
  90953. var engine = scene.getEngine();
  90954. this._ib = engine.createIndexBuffer(this._linesIndices);
  90955. };
  90956. EdgesRenderer.prototype.dispose = function () {
  90957. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90958. if (buffer) {
  90959. buffer.dispose();
  90960. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90961. }
  90962. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90963. if (buffer) {
  90964. buffer.dispose();
  90965. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90966. }
  90967. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90968. this._lineShader.dispose();
  90969. };
  90970. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90971. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90972. return 0;
  90973. }
  90974. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90975. return 1;
  90976. }
  90977. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90978. return 2;
  90979. }
  90980. return -1;
  90981. };
  90982. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90983. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90984. return 0;
  90985. }
  90986. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90987. return 1;
  90988. }
  90989. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90990. return 2;
  90991. }
  90992. return -1;
  90993. };
  90994. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90995. var needToCreateLine;
  90996. if (edge === undefined) {
  90997. needToCreateLine = true;
  90998. }
  90999. else {
  91000. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91001. needToCreateLine = dotProduct < this._epsilon;
  91002. }
  91003. if (needToCreateLine) {
  91004. var offset = this._linesPositions.length / 3;
  91005. var normal = p0.subtract(p1);
  91006. normal.normalize();
  91007. // Positions
  91008. this._linesPositions.push(p0.x);
  91009. this._linesPositions.push(p0.y);
  91010. this._linesPositions.push(p0.z);
  91011. this._linesPositions.push(p0.x);
  91012. this._linesPositions.push(p0.y);
  91013. this._linesPositions.push(p0.z);
  91014. this._linesPositions.push(p1.x);
  91015. this._linesPositions.push(p1.y);
  91016. this._linesPositions.push(p1.z);
  91017. this._linesPositions.push(p1.x);
  91018. this._linesPositions.push(p1.y);
  91019. this._linesPositions.push(p1.z);
  91020. // Normals
  91021. this._linesNormals.push(p1.x);
  91022. this._linesNormals.push(p1.y);
  91023. this._linesNormals.push(p1.z);
  91024. this._linesNormals.push(-1);
  91025. this._linesNormals.push(p1.x);
  91026. this._linesNormals.push(p1.y);
  91027. this._linesNormals.push(p1.z);
  91028. this._linesNormals.push(1);
  91029. this._linesNormals.push(p0.x);
  91030. this._linesNormals.push(p0.y);
  91031. this._linesNormals.push(p0.z);
  91032. this._linesNormals.push(-1);
  91033. this._linesNormals.push(p0.x);
  91034. this._linesNormals.push(p0.y);
  91035. this._linesNormals.push(p0.z);
  91036. this._linesNormals.push(1);
  91037. // Indices
  91038. this._linesIndices.push(offset);
  91039. this._linesIndices.push(offset + 1);
  91040. this._linesIndices.push(offset + 2);
  91041. this._linesIndices.push(offset);
  91042. this._linesIndices.push(offset + 2);
  91043. this._linesIndices.push(offset + 3);
  91044. }
  91045. };
  91046. EdgesRenderer.prototype._generateEdgesLines = function () {
  91047. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91048. var indices = this._source.getIndices();
  91049. if (!indices || !positions) {
  91050. return;
  91051. }
  91052. // First let's find adjacencies
  91053. var adjacencies = new Array();
  91054. var faceNormals = new Array();
  91055. var index;
  91056. var faceAdjacencies;
  91057. // Prepare faces
  91058. for (index = 0; index < indices.length; index += 3) {
  91059. faceAdjacencies = new FaceAdjacencies();
  91060. var p0Index = indices[index];
  91061. var p1Index = indices[index + 1];
  91062. var p2Index = indices[index + 2];
  91063. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91064. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91065. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91066. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91067. faceNormal.normalize();
  91068. faceNormals.push(faceNormal);
  91069. adjacencies.push(faceAdjacencies);
  91070. }
  91071. // Scan
  91072. for (index = 0; index < adjacencies.length; index++) {
  91073. faceAdjacencies = adjacencies[index];
  91074. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91075. var otherFaceAdjacencies = adjacencies[otherIndex];
  91076. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91077. break;
  91078. }
  91079. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91080. continue;
  91081. }
  91082. var otherP0 = indices[otherIndex * 3];
  91083. var otherP1 = indices[otherIndex * 3 + 1];
  91084. var otherP2 = indices[otherIndex * 3 + 2];
  91085. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91086. var otherEdgeIndex = 0;
  91087. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91088. continue;
  91089. }
  91090. switch (edgeIndex) {
  91091. case 0:
  91092. if (this._checkVerticesInsteadOfIndices) {
  91093. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91094. }
  91095. else {
  91096. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91097. }
  91098. break;
  91099. case 1:
  91100. if (this._checkVerticesInsteadOfIndices) {
  91101. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91102. }
  91103. else {
  91104. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91105. }
  91106. break;
  91107. case 2:
  91108. if (this._checkVerticesInsteadOfIndices) {
  91109. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91110. }
  91111. else {
  91112. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91113. }
  91114. break;
  91115. }
  91116. if (otherEdgeIndex === -1) {
  91117. continue;
  91118. }
  91119. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91120. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91121. faceAdjacencies.edgesConnectedCount++;
  91122. otherFaceAdjacencies.edgesConnectedCount++;
  91123. if (faceAdjacencies.edgesConnectedCount === 3) {
  91124. break;
  91125. }
  91126. }
  91127. }
  91128. }
  91129. // Create lines
  91130. for (index = 0; index < adjacencies.length; index++) {
  91131. // 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
  91132. var current = adjacencies[index];
  91133. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91134. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91135. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91136. }
  91137. // Merge into a single mesh
  91138. var engine = this._source.getScene().getEngine();
  91139. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91140. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91141. this._ib = engine.createIndexBuffer(this._linesIndices);
  91142. this._indicesCount = this._linesIndices.length;
  91143. };
  91144. EdgesRenderer.prototype.render = function () {
  91145. var scene = this._source.getScene();
  91146. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91147. return;
  91148. }
  91149. var engine = scene.getEngine();
  91150. this._lineShader._preBind();
  91151. // VBOs
  91152. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91153. scene.resetCachedMaterial();
  91154. this._lineShader.setColor4("color", this._source.edgesColor);
  91155. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91156. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91157. }
  91158. else {
  91159. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91160. }
  91161. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91162. this._lineShader.bind(this._source.getWorldMatrix());
  91163. // Draw order
  91164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91165. this._lineShader.unbind();
  91166. engine.setDepthWrite(true);
  91167. };
  91168. return EdgesRenderer;
  91169. }());
  91170. BABYLON.EdgesRenderer = EdgesRenderer;
  91171. })(BABYLON || (BABYLON = {}));
  91172. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91173. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91174. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91175. s = arguments[i];
  91176. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91177. t[p] = s[p];
  91178. }
  91179. return t;
  91180. };
  91181. var BABYLON;
  91182. (function (BABYLON) {
  91183. /**
  91184. * The effect layer Helps adding post process effect blended with the main pass.
  91185. *
  91186. * This can be for instance use to generate glow or higlight effects on the scene.
  91187. *
  91188. * The effect layer class can not be used directly and is intented to inherited from to be
  91189. * customized per effects.
  91190. */
  91191. var EffectLayer = /** @class */ (function () {
  91192. /**
  91193. * Instantiates a new effect Layer and references it in the scene.
  91194. * @param name The name of the layer
  91195. * @param scene The scene to use the layer in
  91196. */
  91197. function EffectLayer(
  91198. /** The Friendly of the effect in the scene */
  91199. name, scene) {
  91200. this._vertexBuffers = {};
  91201. this._maxSize = 0;
  91202. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91203. this._shouldRender = true;
  91204. this._postProcesses = [];
  91205. this._textures = [];
  91206. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91207. /**
  91208. * The clear color of the texture used to generate the glow map.
  91209. */
  91210. this.neutralColor = new BABYLON.Color4();
  91211. /**
  91212. * Specifies wether the highlight layer is enabled or not.
  91213. */
  91214. this.isEnabled = true;
  91215. /**
  91216. * An event triggered when the effect layer has been disposed.
  91217. */
  91218. this.onDisposeObservable = new BABYLON.Observable();
  91219. /**
  91220. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91221. */
  91222. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91223. /**
  91224. * An event triggered when the generated texture is being merged in the scene.
  91225. */
  91226. this.onBeforeComposeObservable = new BABYLON.Observable();
  91227. /**
  91228. * An event triggered when the generated texture has been merged in the scene.
  91229. */
  91230. this.onAfterComposeObservable = new BABYLON.Observable();
  91231. /**
  91232. * An event triggered when the efffect layer changes its size.
  91233. */
  91234. this.onSizeChangedObservable = new BABYLON.Observable();
  91235. this.name = name;
  91236. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91237. this._engine = scene.getEngine();
  91238. this._maxSize = this._engine.getCaps().maxTextureSize;
  91239. this._scene.effectLayers.push(this);
  91240. // Generate Buffers
  91241. this._generateIndexBuffer();
  91242. this._genrateVertexBuffer();
  91243. }
  91244. Object.defineProperty(EffectLayer.prototype, "camera", {
  91245. /**
  91246. * Gets the camera attached to the layer.
  91247. */
  91248. get: function () {
  91249. return this._effectLayerOptions.camera;
  91250. },
  91251. enumerable: true,
  91252. configurable: true
  91253. });
  91254. /**
  91255. * Initializes the effect layer with the required options.
  91256. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91257. */
  91258. EffectLayer.prototype._init = function (options) {
  91259. // Adapt options
  91260. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91261. this._setMainTextureSize();
  91262. this._createMainTexture();
  91263. this._createTextureAndPostProcesses();
  91264. this._mergeEffect = this._createMergeEffect();
  91265. };
  91266. /**
  91267. * Generates the index buffer of the full screen quad blending to the main canvas.
  91268. */
  91269. EffectLayer.prototype._generateIndexBuffer = function () {
  91270. // Indices
  91271. var indices = [];
  91272. indices.push(0);
  91273. indices.push(1);
  91274. indices.push(2);
  91275. indices.push(0);
  91276. indices.push(2);
  91277. indices.push(3);
  91278. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91279. };
  91280. /**
  91281. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91282. */
  91283. EffectLayer.prototype._genrateVertexBuffer = function () {
  91284. // VBO
  91285. var vertices = [];
  91286. vertices.push(1, 1);
  91287. vertices.push(-1, 1);
  91288. vertices.push(-1, -1);
  91289. vertices.push(1, -1);
  91290. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91292. };
  91293. /**
  91294. * Sets the main texture desired size which is the closest power of two
  91295. * of the engine canvas size.
  91296. */
  91297. EffectLayer.prototype._setMainTextureSize = function () {
  91298. if (this._effectLayerOptions.mainTextureFixedSize) {
  91299. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91300. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91301. }
  91302. else {
  91303. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91304. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91305. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91306. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91307. }
  91308. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91309. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91310. };
  91311. /**
  91312. * Creates the main texture for the effect layer.
  91313. */
  91314. EffectLayer.prototype._createMainTexture = function () {
  91315. var _this = this;
  91316. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91317. width: this._mainTextureDesiredSize.width,
  91318. height: this._mainTextureDesiredSize.height
  91319. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91320. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91321. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91322. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91323. this._mainTexture.anisotropicFilteringLevel = 1;
  91324. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91325. this._mainTexture.renderParticles = false;
  91326. this._mainTexture.renderList = null;
  91327. this._mainTexture.ignoreCameraViewport = true;
  91328. // Custom render function
  91329. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91330. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91331. var index;
  91332. var engine = _this._scene.getEngine();
  91333. if (depthOnlySubMeshes.length) {
  91334. engine.setColorWrite(false);
  91335. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91336. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91337. }
  91338. engine.setColorWrite(true);
  91339. }
  91340. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91341. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91342. }
  91343. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91344. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91345. }
  91346. for (index = 0; index < transparentSubMeshes.length; index++) {
  91347. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91348. }
  91349. };
  91350. this._mainTexture.onClearObservable.add(function (engine) {
  91351. engine.clear(_this.neutralColor, true, true, true);
  91352. });
  91353. };
  91354. /**
  91355. * Checks for the readiness of the element composing the layer.
  91356. * @param subMesh the mesh to check for
  91357. * @param useInstances specify wether or not to use instances to render the mesh
  91358. * @param emissiveTexture the associated emissive texture used to generate the glow
  91359. * @return true if ready otherwise, false
  91360. */
  91361. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91362. var material = subMesh.getMaterial();
  91363. if (!material) {
  91364. return false;
  91365. }
  91366. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91367. return false;
  91368. }
  91369. var defines = [];
  91370. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91371. var mesh = subMesh.getMesh();
  91372. var uv1 = false;
  91373. var uv2 = false;
  91374. // Alpha test
  91375. if (material && material.needAlphaTesting()) {
  91376. var alphaTexture = material.getAlphaTestTexture();
  91377. if (alphaTexture) {
  91378. defines.push("#define ALPHATEST");
  91379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91380. alphaTexture.coordinatesIndex === 1) {
  91381. defines.push("#define DIFFUSEUV2");
  91382. uv2 = true;
  91383. }
  91384. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91385. defines.push("#define DIFFUSEUV1");
  91386. uv1 = true;
  91387. }
  91388. }
  91389. }
  91390. // Emissive
  91391. if (emissiveTexture) {
  91392. defines.push("#define EMISSIVE");
  91393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91394. emissiveTexture.coordinatesIndex === 1) {
  91395. defines.push("#define EMISSIVEUV2");
  91396. uv2 = true;
  91397. }
  91398. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91399. defines.push("#define EMISSIVEUV1");
  91400. uv1 = true;
  91401. }
  91402. }
  91403. if (uv1) {
  91404. attribs.push(BABYLON.VertexBuffer.UVKind);
  91405. defines.push("#define UV1");
  91406. }
  91407. if (uv2) {
  91408. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91409. defines.push("#define UV2");
  91410. }
  91411. // Bones
  91412. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91415. if (mesh.numBoneInfluencers > 4) {
  91416. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91417. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91418. }
  91419. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91420. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91421. }
  91422. else {
  91423. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91424. }
  91425. // Morph targets
  91426. var manager = mesh.morphTargetManager;
  91427. var morphInfluencers = 0;
  91428. if (manager) {
  91429. if (manager.numInfluencers > 0) {
  91430. defines.push("#define MORPHTARGETS");
  91431. morphInfluencers = manager.numInfluencers;
  91432. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91433. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91434. }
  91435. }
  91436. // Instances
  91437. if (useInstances) {
  91438. defines.push("#define INSTANCES");
  91439. attribs.push("world0");
  91440. attribs.push("world1");
  91441. attribs.push("world2");
  91442. attribs.push("world3");
  91443. }
  91444. // Get correct effect
  91445. var join = defines.join("\n");
  91446. if (this._cachedDefines !== join) {
  91447. this._cachedDefines = join;
  91448. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91449. }
  91450. return this._effectLayerMapGenerationEffect.isReady();
  91451. };
  91452. /**
  91453. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91454. */
  91455. EffectLayer.prototype.render = function () {
  91456. var currentEffect = this._mergeEffect;
  91457. // Check
  91458. if (!currentEffect.isReady())
  91459. return;
  91460. for (var i = 0; i < this._postProcesses.length; i++) {
  91461. if (!this._postProcesses[i].isReady()) {
  91462. return;
  91463. }
  91464. }
  91465. var engine = this._scene.getEngine();
  91466. this.onBeforeComposeObservable.notifyObservers(this);
  91467. // Render
  91468. engine.enableEffect(currentEffect);
  91469. engine.setState(false);
  91470. // VBOs
  91471. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91472. // Cache
  91473. var previousAlphaMode = engine.getAlphaMode();
  91474. // Go Blend.
  91475. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91476. // Blends the map on the main canvas.
  91477. this._internalRender(currentEffect);
  91478. // Restore Alpha
  91479. engine.setAlphaMode(previousAlphaMode);
  91480. this.onAfterComposeObservable.notifyObservers(this);
  91481. // Handle size changes.
  91482. var size = this._mainTexture.getSize();
  91483. this._setMainTextureSize();
  91484. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91485. // Recreate RTT and post processes on size change.
  91486. this.onSizeChangedObservable.notifyObservers(this);
  91487. this._disposeTextureAndPostProcesses();
  91488. this._createMainTexture();
  91489. this._createTextureAndPostProcesses();
  91490. }
  91491. };
  91492. /**
  91493. * Determine if a given mesh will be used in the current effect.
  91494. * @param mesh mesh to test
  91495. * @returns true if the mesh will be used
  91496. */
  91497. EffectLayer.prototype.hasMesh = function (mesh) {
  91498. return true;
  91499. };
  91500. /**
  91501. * Returns true if the layer contains information to display, otherwise false.
  91502. * @returns true if the glow layer should be rendered
  91503. */
  91504. EffectLayer.prototype.shouldRender = function () {
  91505. return this.isEnabled && this._shouldRender;
  91506. };
  91507. /**
  91508. * Returns true if the mesh should render, otherwise false.
  91509. * @param mesh The mesh to render
  91510. * @returns true if it should render otherwise false
  91511. */
  91512. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91513. return true;
  91514. };
  91515. /**
  91516. * Returns true if the mesh should render, otherwise false.
  91517. * @param mesh The mesh to render
  91518. * @returns true if it should render otherwise false
  91519. */
  91520. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91521. return true;
  91522. };
  91523. /**
  91524. * Renders the submesh passed in parameter to the generation map.
  91525. */
  91526. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91527. var _this = this;
  91528. if (!this.shouldRender()) {
  91529. return;
  91530. }
  91531. var material = subMesh.getMaterial();
  91532. var mesh = subMesh.getRenderingMesh();
  91533. var scene = this._scene;
  91534. var engine = scene.getEngine();
  91535. if (!material) {
  91536. return;
  91537. }
  91538. // Do not block in blend mode.
  91539. if (material.needAlphaBlendingForMesh(mesh)) {
  91540. return;
  91541. }
  91542. // Culling
  91543. engine.setState(material.backFaceCulling);
  91544. // Managing instances
  91545. var batch = mesh._getInstancesRenderList(subMesh._id);
  91546. if (batch.mustReturn) {
  91547. return;
  91548. }
  91549. // Early Exit per mesh
  91550. if (!this._shouldRenderMesh(mesh)) {
  91551. return;
  91552. }
  91553. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91554. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91555. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91556. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91557. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91558. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91559. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91560. // Alpha test
  91561. if (material && material.needAlphaTesting()) {
  91562. var alphaTexture = material.getAlphaTestTexture();
  91563. if (alphaTexture) {
  91564. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91565. var textureMatrix = alphaTexture.getTextureMatrix();
  91566. if (textureMatrix) {
  91567. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91568. }
  91569. }
  91570. }
  91571. // Glow emissive only
  91572. if (this._emissiveTextureAndColor.texture) {
  91573. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91574. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91575. }
  91576. // Bones
  91577. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91578. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91579. }
  91580. // Morph targets
  91581. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91582. // Draw
  91583. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91584. }
  91585. else {
  91586. // Need to reset refresh rate of the shadowMap
  91587. this._mainTexture.resetRefreshCounter();
  91588. }
  91589. };
  91590. /**
  91591. * Rebuild the required buffers.
  91592. * @hidden Internal use only.
  91593. */
  91594. EffectLayer.prototype._rebuild = function () {
  91595. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91596. if (vb) {
  91597. vb._rebuild();
  91598. }
  91599. this._generateIndexBuffer();
  91600. };
  91601. /**
  91602. * Dispose only the render target textures and post process.
  91603. */
  91604. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91605. this._mainTexture.dispose();
  91606. for (var i = 0; i < this._postProcesses.length; i++) {
  91607. if (this._postProcesses[i]) {
  91608. this._postProcesses[i].dispose();
  91609. }
  91610. }
  91611. this._postProcesses = [];
  91612. for (var i = 0; i < this._textures.length; i++) {
  91613. if (this._textures[i]) {
  91614. this._textures[i].dispose();
  91615. }
  91616. }
  91617. this._textures = [];
  91618. };
  91619. /**
  91620. * Dispose the highlight layer and free resources.
  91621. */
  91622. EffectLayer.prototype.dispose = function () {
  91623. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91624. if (vertexBuffer) {
  91625. vertexBuffer.dispose();
  91626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91627. }
  91628. if (this._indexBuffer) {
  91629. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91630. this._indexBuffer = null;
  91631. }
  91632. // Clean textures and post processes
  91633. this._disposeTextureAndPostProcesses();
  91634. // Remove from scene
  91635. var index = this._scene.effectLayers.indexOf(this, 0);
  91636. if (index > -1) {
  91637. this._scene.effectLayers.splice(index, 1);
  91638. }
  91639. // Callback
  91640. this.onDisposeObservable.notifyObservers(this);
  91641. this.onDisposeObservable.clear();
  91642. this.onBeforeRenderMainTextureObservable.clear();
  91643. this.onBeforeComposeObservable.clear();
  91644. this.onAfterComposeObservable.clear();
  91645. this.onSizeChangedObservable.clear();
  91646. };
  91647. /**
  91648. * Gets the class name of the effect layer
  91649. * @returns the string with the class name of the effect layer
  91650. */
  91651. EffectLayer.prototype.getClassName = function () {
  91652. return "EffectLayer";
  91653. };
  91654. /**
  91655. * Creates an effect layer from parsed effect layer data
  91656. * @param parsedEffectLayer defines effect layer data
  91657. * @param scene defines the current scene
  91658. * @param rootUrl defines the root URL containing the effect layer information
  91659. * @returns a parsed effect Layer
  91660. */
  91661. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91662. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91663. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91664. };
  91665. __decorate([
  91666. BABYLON.serialize()
  91667. ], EffectLayer.prototype, "name", void 0);
  91668. __decorate([
  91669. BABYLON.serializeAsColor4()
  91670. ], EffectLayer.prototype, "neutralColor", void 0);
  91671. __decorate([
  91672. BABYLON.serialize()
  91673. ], EffectLayer.prototype, "isEnabled", void 0);
  91674. __decorate([
  91675. BABYLON.serializeAsCameraReference()
  91676. ], EffectLayer.prototype, "camera", null);
  91677. return EffectLayer;
  91678. }());
  91679. BABYLON.EffectLayer = EffectLayer;
  91680. })(BABYLON || (BABYLON = {}));
  91681. //# sourceMappingURL=babylon.effectLayer.js.map
  91682. var BABYLON;
  91683. (function (BABYLON) {
  91684. /**
  91685. * Special Glow Blur post process only blurring the alpha channel
  91686. * It enforces keeping the most luminous color in the color channel.
  91687. */
  91688. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91689. __extends(GlowBlurPostProcess, _super);
  91690. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91692. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91693. _this.direction = direction;
  91694. _this.kernel = kernel;
  91695. _this.onApplyObservable.add(function (effect) {
  91696. effect.setFloat2("screenSize", _this.width, _this.height);
  91697. effect.setVector2("direction", _this.direction);
  91698. effect.setFloat("blurWidth", _this.kernel);
  91699. });
  91700. return _this;
  91701. }
  91702. return GlowBlurPostProcess;
  91703. }(BABYLON.PostProcess));
  91704. /**
  91705. * The highlight layer Helps adding a glow effect around a mesh.
  91706. *
  91707. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91708. * glowy meshes to your scene.
  91709. *
  91710. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91711. */
  91712. var HighlightLayer = /** @class */ (function (_super) {
  91713. __extends(HighlightLayer, _super);
  91714. /**
  91715. * Instantiates a new highlight Layer and references it to the scene..
  91716. * @param name The name of the layer
  91717. * @param scene The scene to use the layer in
  91718. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91719. */
  91720. function HighlightLayer(name, scene, options) {
  91721. var _this = _super.call(this, name, scene) || this;
  91722. _this.name = name;
  91723. /**
  91724. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91725. */
  91726. _this.innerGlow = true;
  91727. /**
  91728. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91729. */
  91730. _this.outerGlow = true;
  91731. /**
  91732. * An event triggered when the highlight layer is being blurred.
  91733. */
  91734. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91735. /**
  91736. * An event triggered when the highlight layer has been blurred.
  91737. */
  91738. _this.onAfterBlurObservable = new BABYLON.Observable();
  91739. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91740. _this._meshes = {};
  91741. _this._excludedMeshes = {};
  91742. _this.neutralColor = HighlightLayer.NeutralColor;
  91743. // Warn on stencil
  91744. if (!_this._engine.isStencilEnable) {
  91745. 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 }");
  91746. }
  91747. // Adapt options
  91748. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91749. // Initialize the layer
  91750. _this._init({
  91751. alphaBlendingMode: _this._options.alphaBlendingMode,
  91752. camera: _this._options.camera,
  91753. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91754. mainTextureRatio: _this._options.mainTextureRatio
  91755. });
  91756. // Do not render as long as no meshes have been added
  91757. _this._shouldRender = false;
  91758. return _this;
  91759. }
  91760. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91761. /**
  91762. * Gets the horizontal size of the blur.
  91763. */
  91764. get: function () {
  91765. return this._horizontalBlurPostprocess.kernel;
  91766. },
  91767. /**
  91768. * Specifies the horizontal size of the blur.
  91769. */
  91770. set: function (value) {
  91771. this._horizontalBlurPostprocess.kernel = value;
  91772. },
  91773. enumerable: true,
  91774. configurable: true
  91775. });
  91776. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91777. /**
  91778. * Gets the vertical size of the blur.
  91779. */
  91780. get: function () {
  91781. return this._verticalBlurPostprocess.kernel;
  91782. },
  91783. /**
  91784. * Specifies the vertical size of the blur.
  91785. */
  91786. set: function (value) {
  91787. this._verticalBlurPostprocess.kernel = value;
  91788. },
  91789. enumerable: true,
  91790. configurable: true
  91791. });
  91792. /**
  91793. * Get the effect name of the layer.
  91794. * @return The effect name
  91795. */
  91796. HighlightLayer.prototype.getEffectName = function () {
  91797. return HighlightLayer.EffectName;
  91798. };
  91799. /**
  91800. * Create the merge effect. This is the shader use to blit the information back
  91801. * to the main canvas at the end of the scene rendering.
  91802. */
  91803. HighlightLayer.prototype._createMergeEffect = function () {
  91804. // Effect
  91805. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91806. };
  91807. /**
  91808. * Creates the render target textures and post processes used in the highlight layer.
  91809. */
  91810. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91811. var _this = this;
  91812. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91813. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91814. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91815. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91816. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91817. width: blurTextureWidth,
  91818. height: blurTextureHeight
  91819. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91820. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91821. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91822. this._blurTexture.anisotropicFilteringLevel = 16;
  91823. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91824. this._blurTexture.renderParticles = false;
  91825. this._blurTexture.ignoreCameraViewport = true;
  91826. this._textures = [this._blurTexture];
  91827. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91828. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91829. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91830. effect.setTexture("textureSampler", _this._mainTexture);
  91831. });
  91832. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91833. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91834. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91835. });
  91836. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91837. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91838. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91839. });
  91840. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91841. }
  91842. else {
  91843. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91844. width: blurTextureWidth,
  91845. height: blurTextureHeight
  91846. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91847. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91848. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91849. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91850. effect.setTexture("textureSampler", _this._mainTexture);
  91851. });
  91852. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91853. width: blurTextureWidth,
  91854. height: blurTextureHeight
  91855. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91856. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91857. }
  91858. this._mainTexture.onAfterUnbindObservable.add(function () {
  91859. _this.onBeforeBlurObservable.notifyObservers(_this);
  91860. var internalTexture = _this._blurTexture.getInternalTexture();
  91861. if (internalTexture) {
  91862. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91863. }
  91864. _this.onAfterBlurObservable.notifyObservers(_this);
  91865. });
  91866. // Prevent autoClear.
  91867. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91868. };
  91869. /**
  91870. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91871. */
  91872. HighlightLayer.prototype.needStencil = function () {
  91873. return true;
  91874. };
  91875. /**
  91876. * Checks for the readiness of the element composing the layer.
  91877. * @param subMesh the mesh to check for
  91878. * @param useInstances specify wether or not to use instances to render the mesh
  91879. * @param emissiveTexture the associated emissive texture used to generate the glow
  91880. * @return true if ready otherwise, false
  91881. */
  91882. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91883. var material = subMesh.getMaterial();
  91884. var mesh = subMesh.getRenderingMesh();
  91885. if (!material || !mesh || !this._meshes) {
  91886. return false;
  91887. }
  91888. var emissiveTexture = null;
  91889. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91890. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91891. emissiveTexture = material.emissiveTexture;
  91892. }
  91893. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91894. };
  91895. /**
  91896. * Implementation specific of rendering the generating effect on the main canvas.
  91897. * @param effect The effect used to render through
  91898. */
  91899. HighlightLayer.prototype._internalRender = function (effect) {
  91900. // Texture
  91901. effect.setTexture("textureSampler", this._blurTexture);
  91902. // Cache
  91903. var engine = this._engine;
  91904. var previousStencilBuffer = engine.getStencilBuffer();
  91905. var previousStencilFunction = engine.getStencilFunction();
  91906. var previousStencilMask = engine.getStencilMask();
  91907. var previousStencilOperationPass = engine.getStencilOperationPass();
  91908. var previousStencilOperationFail = engine.getStencilOperationFail();
  91909. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91910. var previousStencilReference = engine.getStencilFunctionReference();
  91911. // Stencil operations
  91912. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91913. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91914. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91915. // Draw order
  91916. engine.setStencilMask(0x00);
  91917. engine.setStencilBuffer(true);
  91918. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91919. // 2 passes inner outer
  91920. if (this.outerGlow) {
  91921. effect.setFloat("offset", 0);
  91922. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91924. }
  91925. if (this.innerGlow) {
  91926. effect.setFloat("offset", 1);
  91927. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91928. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91929. }
  91930. // Restore Cache
  91931. engine.setStencilFunction(previousStencilFunction);
  91932. engine.setStencilMask(previousStencilMask);
  91933. engine.setStencilBuffer(previousStencilBuffer);
  91934. engine.setStencilOperationPass(previousStencilOperationPass);
  91935. engine.setStencilOperationFail(previousStencilOperationFail);
  91936. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91937. engine.setStencilFunctionReference(previousStencilReference);
  91938. };
  91939. /**
  91940. * Returns true if the layer contains information to display, otherwise false.
  91941. */
  91942. HighlightLayer.prototype.shouldRender = function () {
  91943. if (_super.prototype.shouldRender.call(this)) {
  91944. return this._meshes ? true : false;
  91945. }
  91946. return false;
  91947. };
  91948. /**
  91949. * Returns true if the mesh should render, otherwise false.
  91950. * @param mesh The mesh to render
  91951. * @returns true if it should render otherwise false
  91952. */
  91953. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91954. // Excluded Mesh
  91955. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91956. return false;
  91957. }
  91958. ;
  91959. return true;
  91960. };
  91961. /**
  91962. * Sets the required values for both the emissive texture and and the main color.
  91963. */
  91964. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91965. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91966. if (highlightLayerMesh) {
  91967. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91968. }
  91969. else {
  91970. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91971. }
  91972. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91973. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91974. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91975. }
  91976. else {
  91977. this._emissiveTextureAndColor.texture = null;
  91978. }
  91979. };
  91980. /**
  91981. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91982. * @param mesh The mesh to exclude from the highlight layer
  91983. */
  91984. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91985. if (!this._excludedMeshes) {
  91986. return;
  91987. }
  91988. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91989. if (!meshExcluded) {
  91990. this._excludedMeshes[mesh.uniqueId] = {
  91991. mesh: mesh,
  91992. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91993. mesh.getEngine().setStencilBuffer(false);
  91994. }),
  91995. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91996. mesh.getEngine().setStencilBuffer(true);
  91997. }),
  91998. };
  91999. }
  92000. };
  92001. /**
  92002. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92003. * @param mesh The mesh to highlight
  92004. */
  92005. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92006. if (!this._excludedMeshes) {
  92007. return;
  92008. }
  92009. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92010. if (meshExcluded) {
  92011. if (meshExcluded.beforeRender) {
  92012. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92013. }
  92014. if (meshExcluded.afterRender) {
  92015. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92016. }
  92017. }
  92018. this._excludedMeshes[mesh.uniqueId] = null;
  92019. };
  92020. /**
  92021. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92022. * @param mesh mesh to test
  92023. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92024. */
  92025. HighlightLayer.prototype.hasMesh = function (mesh) {
  92026. if (!this._meshes) {
  92027. return false;
  92028. }
  92029. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92030. };
  92031. /**
  92032. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92033. * @param mesh The mesh to highlight
  92034. * @param color The color of the highlight
  92035. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92036. */
  92037. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92038. var _this = this;
  92039. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92040. if (!this._meshes) {
  92041. return;
  92042. }
  92043. var meshHighlight = this._meshes[mesh.uniqueId];
  92044. if (meshHighlight) {
  92045. meshHighlight.color = color;
  92046. }
  92047. else {
  92048. this._meshes[mesh.uniqueId] = {
  92049. mesh: mesh,
  92050. color: color,
  92051. // Lambda required for capture due to Observable this context
  92052. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92053. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92054. _this._defaultStencilReference(mesh);
  92055. }
  92056. else {
  92057. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92058. }
  92059. }),
  92060. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92061. glowEmissiveOnly: glowEmissiveOnly
  92062. };
  92063. }
  92064. this._shouldRender = true;
  92065. };
  92066. /**
  92067. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92068. * @param mesh The mesh to highlight
  92069. */
  92070. HighlightLayer.prototype.removeMesh = function (mesh) {
  92071. if (!this._meshes) {
  92072. return;
  92073. }
  92074. var meshHighlight = this._meshes[mesh.uniqueId];
  92075. if (meshHighlight) {
  92076. if (meshHighlight.observerHighlight) {
  92077. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92078. }
  92079. if (meshHighlight.observerDefault) {
  92080. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92081. }
  92082. delete this._meshes[mesh.uniqueId];
  92083. }
  92084. this._shouldRender = false;
  92085. for (var meshHighlightToCheck in this._meshes) {
  92086. if (this._meshes[meshHighlightToCheck]) {
  92087. this._shouldRender = true;
  92088. break;
  92089. }
  92090. }
  92091. };
  92092. /**
  92093. * Force the stencil to the normal expected value for none glowing parts
  92094. */
  92095. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92096. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92097. };
  92098. /**
  92099. * Free any resources and references associated to a mesh.
  92100. * Internal use
  92101. * @param mesh The mesh to free.
  92102. */
  92103. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92104. this.removeMesh(mesh);
  92105. this.removeExcludedMesh(mesh);
  92106. };
  92107. /**
  92108. * Dispose the highlight layer and free resources.
  92109. */
  92110. HighlightLayer.prototype.dispose = function () {
  92111. if (this._meshes) {
  92112. // Clean mesh references
  92113. for (var id in this._meshes) {
  92114. var meshHighlight = this._meshes[id];
  92115. if (meshHighlight && meshHighlight.mesh) {
  92116. if (meshHighlight.observerHighlight) {
  92117. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92118. }
  92119. if (meshHighlight.observerDefault) {
  92120. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92121. }
  92122. }
  92123. }
  92124. this._meshes = null;
  92125. }
  92126. if (this._excludedMeshes) {
  92127. for (var id in this._excludedMeshes) {
  92128. var meshHighlight = this._excludedMeshes[id];
  92129. if (meshHighlight) {
  92130. if (meshHighlight.beforeRender) {
  92131. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92132. }
  92133. if (meshHighlight.afterRender) {
  92134. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92135. }
  92136. }
  92137. }
  92138. this._excludedMeshes = null;
  92139. }
  92140. _super.prototype.dispose.call(this);
  92141. };
  92142. /**
  92143. * Gets the class name of the effect layer
  92144. * @returns the string with the class name of the effect layer
  92145. */
  92146. HighlightLayer.prototype.getClassName = function () {
  92147. return "HighlightLayer";
  92148. };
  92149. /**
  92150. * Serializes this Highlight layer
  92151. * @returns a serialized Highlight layer object
  92152. */
  92153. HighlightLayer.prototype.serialize = function () {
  92154. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92155. serializationObject.customType = "BABYLON.HighlightLayer";
  92156. // Highlighted meshes
  92157. serializationObject.meshes = [];
  92158. if (this._meshes) {
  92159. for (var m in this._meshes) {
  92160. var mesh = this._meshes[m];
  92161. if (mesh) {
  92162. serializationObject.meshes.push({
  92163. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92164. color: mesh.color.asArray(),
  92165. meshId: mesh.mesh.id
  92166. });
  92167. }
  92168. }
  92169. }
  92170. // Excluded meshes
  92171. serializationObject.excludedMeshes = [];
  92172. if (this._excludedMeshes) {
  92173. for (var e in this._excludedMeshes) {
  92174. var excludedMesh = this._excludedMeshes[e];
  92175. if (excludedMesh) {
  92176. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92177. }
  92178. }
  92179. }
  92180. return serializationObject;
  92181. };
  92182. /**
  92183. * Creates a Highlight layer from parsed Highlight layer data
  92184. * @param parsedHightlightLayer defines the Highlight layer data
  92185. * @param scene defines the current scene
  92186. * @param rootUrl defines the root URL containing the Highlight layer information
  92187. * @returns a parsed Highlight layer
  92188. */
  92189. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92190. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92191. var index;
  92192. // Excluded meshes
  92193. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92194. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92195. if (mesh) {
  92196. hl.addExcludedMesh(mesh);
  92197. }
  92198. }
  92199. // Included meshes
  92200. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92201. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92202. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92203. if (mesh) {
  92204. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92205. }
  92206. }
  92207. return hl;
  92208. };
  92209. /**
  92210. * Effect Name of the highlight layer.
  92211. */
  92212. HighlightLayer.EffectName = "HighlightLayer";
  92213. /**
  92214. * The neutral color used during the preparation of the glow effect.
  92215. * This is black by default as the blend operation is a blend operation.
  92216. */
  92217. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92218. /**
  92219. * Stencil value used for glowing meshes.
  92220. */
  92221. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92222. /**
  92223. * Stencil value used for the other meshes in the scene.
  92224. */
  92225. HighlightLayer.NormalMeshStencilReference = 0x01;
  92226. __decorate([
  92227. BABYLON.serialize()
  92228. ], HighlightLayer.prototype, "innerGlow", void 0);
  92229. __decorate([
  92230. BABYLON.serialize()
  92231. ], HighlightLayer.prototype, "outerGlow", void 0);
  92232. __decorate([
  92233. BABYLON.serialize()
  92234. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92235. __decorate([
  92236. BABYLON.serialize()
  92237. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92238. __decorate([
  92239. BABYLON.serialize("options")
  92240. ], HighlightLayer.prototype, "_options", void 0);
  92241. return HighlightLayer;
  92242. }(BABYLON.EffectLayer));
  92243. BABYLON.HighlightLayer = HighlightLayer;
  92244. })(BABYLON || (BABYLON = {}));
  92245. //# sourceMappingURL=babylon.highlightLayer.js.map
  92246. var BABYLON;
  92247. (function (BABYLON) {
  92248. /**
  92249. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92250. *
  92251. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92252. * glowy meshes to your scene.
  92253. *
  92254. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92255. */
  92256. var GlowLayer = /** @class */ (function (_super) {
  92257. __extends(GlowLayer, _super);
  92258. /**
  92259. * Instantiates a new glow Layer and references it to the scene.
  92260. * @param name The name of the layer
  92261. * @param scene The scene to use the layer in
  92262. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92263. */
  92264. function GlowLayer(name, scene, options) {
  92265. var _this = _super.call(this, name, scene) || this;
  92266. _this._intensity = 1.0;
  92267. _this._includedOnlyMeshes = [];
  92268. _this._excludedMeshes = [];
  92269. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92270. // Adapt options
  92271. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92272. // Initialize the layer
  92273. _this._init({
  92274. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92275. camera: _this._options.camera,
  92276. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92277. mainTextureRatio: _this._options.mainTextureRatio
  92278. });
  92279. return _this;
  92280. }
  92281. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92282. /**
  92283. * Gets the kernel size of the blur.
  92284. */
  92285. get: function () {
  92286. return this._horizontalBlurPostprocess1.kernel;
  92287. },
  92288. /**
  92289. * Sets the kernel size of the blur.
  92290. */
  92291. set: function (value) {
  92292. this._horizontalBlurPostprocess1.kernel = value;
  92293. this._verticalBlurPostprocess1.kernel = value;
  92294. this._horizontalBlurPostprocess2.kernel = value;
  92295. this._verticalBlurPostprocess2.kernel = value;
  92296. },
  92297. enumerable: true,
  92298. configurable: true
  92299. });
  92300. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92301. /**
  92302. * Gets the glow intensity.
  92303. */
  92304. get: function () {
  92305. return this._intensity;
  92306. },
  92307. /**
  92308. * Sets the glow intensity.
  92309. */
  92310. set: function (value) {
  92311. this._intensity = value;
  92312. },
  92313. enumerable: true,
  92314. configurable: true
  92315. });
  92316. /**
  92317. * Get the effect name of the layer.
  92318. * @return The effect name
  92319. */
  92320. GlowLayer.prototype.getEffectName = function () {
  92321. return GlowLayer.EffectName;
  92322. };
  92323. /**
  92324. * Create the merge effect. This is the shader use to blit the information back
  92325. * to the main canvas at the end of the scene rendering.
  92326. */
  92327. GlowLayer.prototype._createMergeEffect = function () {
  92328. // Effect
  92329. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92330. };
  92331. /**
  92332. * Creates the render target textures and post processes used in the glow layer.
  92333. */
  92334. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92335. var _this = this;
  92336. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92337. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92338. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92339. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92340. var textureType = 0;
  92341. if (this._engine.getCaps().textureHalfFloatRender) {
  92342. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92343. }
  92344. else {
  92345. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92346. }
  92347. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92348. width: blurTextureWidth,
  92349. height: blurTextureHeight
  92350. }, this._scene, false, true, textureType);
  92351. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92352. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92353. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92354. this._blurTexture1.renderParticles = false;
  92355. this._blurTexture1.ignoreCameraViewport = true;
  92356. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92357. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92358. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92359. width: blurTextureWidth2,
  92360. height: blurTextureHeight2
  92361. }, this._scene, false, true, textureType);
  92362. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92363. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92364. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92365. this._blurTexture2.renderParticles = false;
  92366. this._blurTexture2.ignoreCameraViewport = true;
  92367. this._textures = [this._blurTexture1, this._blurTexture2];
  92368. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92369. width: blurTextureWidth,
  92370. height: blurTextureHeight
  92371. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92372. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92373. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92374. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92375. effect.setTexture("textureSampler", _this._mainTexture);
  92376. });
  92377. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92378. width: blurTextureWidth,
  92379. height: blurTextureHeight
  92380. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92381. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92382. width: blurTextureWidth2,
  92383. height: blurTextureHeight2
  92384. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92385. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92386. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92387. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92388. effect.setTexture("textureSampler", _this._blurTexture1);
  92389. });
  92390. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92391. width: blurTextureWidth2,
  92392. height: blurTextureHeight2
  92393. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92394. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92395. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92396. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92397. this._mainTexture.samples = this._options.mainTextureSamples;
  92398. this._mainTexture.onAfterUnbindObservable.add(function () {
  92399. var internalTexture = _this._blurTexture1.getInternalTexture();
  92400. if (internalTexture) {
  92401. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92402. internalTexture = _this._blurTexture2.getInternalTexture();
  92403. if (internalTexture) {
  92404. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92405. }
  92406. }
  92407. });
  92408. // Prevent autoClear.
  92409. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92410. };
  92411. /**
  92412. * Checks for the readiness of the element composing the layer.
  92413. * @param subMesh the mesh to check for
  92414. * @param useInstances specify wether or not to use instances to render the mesh
  92415. * @param emissiveTexture the associated emissive texture used to generate the glow
  92416. * @return true if ready otherwise, false
  92417. */
  92418. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92419. var material = subMesh.getMaterial();
  92420. var mesh = subMesh.getRenderingMesh();
  92421. if (!material || !mesh) {
  92422. return false;
  92423. }
  92424. var emissiveTexture = material.emissiveTexture;
  92425. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92426. };
  92427. /**
  92428. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92429. */
  92430. GlowLayer.prototype.needStencil = function () {
  92431. return false;
  92432. };
  92433. /**
  92434. * Implementation specific of rendering the generating effect on the main canvas.
  92435. * @param effect The effect used to render through
  92436. */
  92437. GlowLayer.prototype._internalRender = function (effect) {
  92438. // Texture
  92439. effect.setTexture("textureSampler", this._blurTexture1);
  92440. effect.setTexture("textureSampler2", this._blurTexture2);
  92441. effect.setFloat("offset", this._intensity);
  92442. // Cache
  92443. var engine = this._engine;
  92444. var previousStencilBuffer = engine.getStencilBuffer();
  92445. // Draw order
  92446. engine.setStencilBuffer(false);
  92447. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92448. // Draw order
  92449. engine.setStencilBuffer(previousStencilBuffer);
  92450. };
  92451. /**
  92452. * Sets the required values for both the emissive texture and and the main color.
  92453. */
  92454. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92455. var textureLevel = 1.0;
  92456. if (this.customEmissiveTextureSelector) {
  92457. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92458. }
  92459. else {
  92460. if (material) {
  92461. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92462. if (this._emissiveTextureAndColor.texture) {
  92463. textureLevel = this._emissiveTextureAndColor.texture.level;
  92464. }
  92465. }
  92466. else {
  92467. this._emissiveTextureAndColor.texture = null;
  92468. }
  92469. }
  92470. if (this.customEmissiveColorSelector) {
  92471. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92472. }
  92473. else {
  92474. if (material.emissiveColor) {
  92475. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92476. }
  92477. else {
  92478. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92479. }
  92480. }
  92481. };
  92482. /**
  92483. * Returns true if the mesh should render, otherwise false.
  92484. * @param mesh The mesh to render
  92485. * @returns true if it should render otherwise false
  92486. */
  92487. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92488. return this.hasMesh(mesh);
  92489. };
  92490. /**
  92491. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92492. * @param mesh The mesh to exclude from the glow layer
  92493. */
  92494. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92495. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92496. this._excludedMeshes.push(mesh.uniqueId);
  92497. }
  92498. };
  92499. /**
  92500. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92501. * @param mesh The mesh to remove
  92502. */
  92503. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92504. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92505. if (index !== -1) {
  92506. this._excludedMeshes.splice(index, 1);
  92507. }
  92508. };
  92509. /**
  92510. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92511. * @param mesh The mesh to include in the glow layer
  92512. */
  92513. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92514. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92515. this._includedOnlyMeshes.push(mesh.uniqueId);
  92516. }
  92517. };
  92518. /**
  92519. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92520. * @param mesh The mesh to remove
  92521. */
  92522. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92523. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92524. if (index !== -1) {
  92525. this._includedOnlyMeshes.splice(index, 1);
  92526. }
  92527. };
  92528. /**
  92529. * Determine if a given mesh will be used in the glow layer
  92530. * @param mesh The mesh to test
  92531. * @returns true if the mesh will be highlighted by the current glow layer
  92532. */
  92533. GlowLayer.prototype.hasMesh = function (mesh) {
  92534. // Included Mesh
  92535. if (this._includedOnlyMeshes.length) {
  92536. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92537. }
  92538. ;
  92539. // Excluded Mesh
  92540. if (this._excludedMeshes.length) {
  92541. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92542. }
  92543. ;
  92544. return true;
  92545. };
  92546. /**
  92547. * Free any resources and references associated to a mesh.
  92548. * Internal use
  92549. * @param mesh The mesh to free.
  92550. */
  92551. GlowLayer.prototype._disposeMesh = function (mesh) {
  92552. this.removeIncludedOnlyMesh(mesh);
  92553. this.removeExcludedMesh(mesh);
  92554. };
  92555. /**
  92556. * Gets the class name of the effect layer
  92557. * @returns the string with the class name of the effect layer
  92558. */
  92559. GlowLayer.prototype.getClassName = function () {
  92560. return "GlowLayer";
  92561. };
  92562. /**
  92563. * Serializes this glow layer
  92564. * @returns a serialized glow layer object
  92565. */
  92566. GlowLayer.prototype.serialize = function () {
  92567. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92568. serializationObject.customType = "BABYLON.GlowLayer";
  92569. var index;
  92570. // Included meshes
  92571. serializationObject.includedMeshes = [];
  92572. if (this._includedOnlyMeshes.length) {
  92573. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92574. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92575. if (mesh) {
  92576. serializationObject.includedMeshes.push(mesh.id);
  92577. }
  92578. }
  92579. }
  92580. // Excluded meshes
  92581. serializationObject.excludedMeshes = [];
  92582. if (this._excludedMeshes.length) {
  92583. for (index = 0; index < this._excludedMeshes.length; index++) {
  92584. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92585. if (mesh) {
  92586. serializationObject.excludedMeshes.push(mesh.id);
  92587. }
  92588. }
  92589. }
  92590. return serializationObject;
  92591. };
  92592. /**
  92593. * Creates a Glow Layer from parsed glow layer data
  92594. * @param parsedGlowLayer defines glow layer data
  92595. * @param scene defines the current scene
  92596. * @param rootUrl defines the root URL containing the glow layer information
  92597. * @returns a parsed Glow Layer
  92598. */
  92599. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92600. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92601. var index;
  92602. // Excluded meshes
  92603. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92604. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92605. if (mesh) {
  92606. gl.addExcludedMesh(mesh);
  92607. }
  92608. }
  92609. // Included meshes
  92610. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92611. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92612. if (mesh) {
  92613. gl.addIncludedOnlyMesh(mesh);
  92614. }
  92615. }
  92616. return gl;
  92617. };
  92618. /**
  92619. * Effect Name of the layer.
  92620. */
  92621. GlowLayer.EffectName = "GlowLayer";
  92622. /**
  92623. * The default blur kernel size used for the glow.
  92624. */
  92625. GlowLayer.DefaultBlurKernelSize = 32;
  92626. /**
  92627. * The default texture size ratio used for the glow.
  92628. */
  92629. GlowLayer.DefaultTextureRatio = 0.5;
  92630. __decorate([
  92631. BABYLON.serialize()
  92632. ], GlowLayer.prototype, "blurKernelSize", null);
  92633. __decorate([
  92634. BABYLON.serialize()
  92635. ], GlowLayer.prototype, "intensity", null);
  92636. __decorate([
  92637. BABYLON.serialize("options")
  92638. ], GlowLayer.prototype, "_options", void 0);
  92639. return GlowLayer;
  92640. }(BABYLON.EffectLayer));
  92641. BABYLON.GlowLayer = GlowLayer;
  92642. })(BABYLON || (BABYLON = {}));
  92643. //# sourceMappingURL=babylon.glowLayer.js.map
  92644. var BABYLON;
  92645. (function (BABYLON) {
  92646. /**
  92647. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92648. */
  92649. var AssetTaskState;
  92650. (function (AssetTaskState) {
  92651. /**
  92652. * Initialization
  92653. */
  92654. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92655. /**
  92656. * Running
  92657. */
  92658. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92659. /**
  92660. * Done
  92661. */
  92662. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92663. /**
  92664. * Error
  92665. */
  92666. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92667. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92668. /**
  92669. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92670. */
  92671. var AbstractAssetTask = /** @class */ (function () {
  92672. /**
  92673. * Creates a new {BABYLON.AssetsManager}
  92674. * @param name defines the name of the task
  92675. */
  92676. function AbstractAssetTask(
  92677. /**
  92678. * Task name
  92679. */ name) {
  92680. this.name = name;
  92681. this._isCompleted = false;
  92682. this._taskState = AssetTaskState.INIT;
  92683. }
  92684. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92685. /**
  92686. * Get if the task is completed
  92687. */
  92688. get: function () {
  92689. return this._isCompleted;
  92690. },
  92691. enumerable: true,
  92692. configurable: true
  92693. });
  92694. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92695. /**
  92696. * Gets the current state of the task
  92697. */
  92698. get: function () {
  92699. return this._taskState;
  92700. },
  92701. enumerable: true,
  92702. configurable: true
  92703. });
  92704. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92705. /**
  92706. * Gets the current error object (if task is in error)
  92707. */
  92708. get: function () {
  92709. return this._errorObject;
  92710. },
  92711. enumerable: true,
  92712. configurable: true
  92713. });
  92714. /**
  92715. * Internal only
  92716. * @hidden
  92717. */
  92718. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92719. if (this._errorObject) {
  92720. return;
  92721. }
  92722. this._errorObject = {
  92723. message: message,
  92724. exception: exception
  92725. };
  92726. };
  92727. /**
  92728. * Execute the current task
  92729. * @param scene defines the scene where you want your assets to be loaded
  92730. * @param onSuccess is a callback called when the task is successfully executed
  92731. * @param onError is a callback called if an error occurs
  92732. */
  92733. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92734. var _this = this;
  92735. this._taskState = AssetTaskState.RUNNING;
  92736. this.runTask(scene, function () {
  92737. _this.onDoneCallback(onSuccess, onError);
  92738. }, function (msg, exception) {
  92739. _this.onErrorCallback(onError, msg, exception);
  92740. });
  92741. };
  92742. /**
  92743. * Execute the current task
  92744. * @param scene defines the scene where you want your assets to be loaded
  92745. * @param onSuccess is a callback called when the task is successfully executed
  92746. * @param onError is a callback called if an error occurs
  92747. */
  92748. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92749. throw new Error("runTask is not implemented");
  92750. };
  92751. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92752. this._taskState = AssetTaskState.ERROR;
  92753. this._errorObject = {
  92754. message: message,
  92755. exception: exception
  92756. };
  92757. if (this.onError) {
  92758. this.onError(this, message, exception);
  92759. }
  92760. onError();
  92761. };
  92762. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92763. try {
  92764. this._taskState = AssetTaskState.DONE;
  92765. this._isCompleted = true;
  92766. if (this.onSuccess) {
  92767. this.onSuccess(this);
  92768. }
  92769. onSuccess();
  92770. }
  92771. catch (e) {
  92772. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92773. }
  92774. };
  92775. return AbstractAssetTask;
  92776. }());
  92777. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92778. /**
  92779. * Class used to share progress information about assets loading
  92780. */
  92781. var AssetsProgressEvent = /** @class */ (function () {
  92782. /**
  92783. * Creates a {BABYLON.AssetsProgressEvent}
  92784. * @param remainingCount defines the number of remaining tasks to process
  92785. * @param totalCount defines the total number of tasks
  92786. * @param task defines the task that was just processed
  92787. */
  92788. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92789. this.remainingCount = remainingCount;
  92790. this.totalCount = totalCount;
  92791. this.task = task;
  92792. }
  92793. return AssetsProgressEvent;
  92794. }());
  92795. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92796. /**
  92797. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92798. */
  92799. var MeshAssetTask = /** @class */ (function (_super) {
  92800. __extends(MeshAssetTask, _super);
  92801. /**
  92802. * Creates a new {BABYLON.MeshAssetTask}
  92803. * @param name defines the name of the task
  92804. * @param meshesNames defines the list of mesh's names you want to load
  92805. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92806. * @param sceneFilename defines the filename of the scene to load from
  92807. */
  92808. function MeshAssetTask(
  92809. /**
  92810. * Defines the name of the task
  92811. */
  92812. name,
  92813. /**
  92814. * Defines the list of mesh's names you want to load
  92815. */
  92816. meshesNames,
  92817. /**
  92818. * Defines the root url to use as a base to load your meshes and associated resources
  92819. */
  92820. rootUrl,
  92821. /**
  92822. * Defines the filename of the scene to load from
  92823. */
  92824. sceneFilename) {
  92825. var _this = _super.call(this, name) || this;
  92826. _this.name = name;
  92827. _this.meshesNames = meshesNames;
  92828. _this.rootUrl = rootUrl;
  92829. _this.sceneFilename = sceneFilename;
  92830. return _this;
  92831. }
  92832. /**
  92833. * Execute the current task
  92834. * @param scene defines the scene where you want your assets to be loaded
  92835. * @param onSuccess is a callback called when the task is successfully executed
  92836. * @param onError is a callback called if an error occurs
  92837. */
  92838. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92839. var _this = this;
  92840. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92841. _this.loadedMeshes = meshes;
  92842. _this.loadedParticleSystems = particleSystems;
  92843. _this.loadedSkeletons = skeletons;
  92844. onSuccess();
  92845. }, null, function (scene, message, exception) {
  92846. onError(message, exception);
  92847. });
  92848. };
  92849. return MeshAssetTask;
  92850. }(AbstractAssetTask));
  92851. BABYLON.MeshAssetTask = MeshAssetTask;
  92852. /**
  92853. * Define a task used by {BABYLON.AssetsManager} to load text content
  92854. */
  92855. var TextFileAssetTask = /** @class */ (function (_super) {
  92856. __extends(TextFileAssetTask, _super);
  92857. /**
  92858. * Creates a new TextFileAssetTask object
  92859. * @param name defines the name of the task
  92860. * @param url defines the location of the file to load
  92861. */
  92862. function TextFileAssetTask(
  92863. /**
  92864. * Defines the name of the task
  92865. */
  92866. name,
  92867. /**
  92868. * Defines the location of the file to load
  92869. */
  92870. url) {
  92871. var _this = _super.call(this, name) || this;
  92872. _this.name = name;
  92873. _this.url = url;
  92874. return _this;
  92875. }
  92876. /**
  92877. * Execute the current task
  92878. * @param scene defines the scene where you want your assets to be loaded
  92879. * @param onSuccess is a callback called when the task is successfully executed
  92880. * @param onError is a callback called if an error occurs
  92881. */
  92882. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92883. var _this = this;
  92884. scene._loadFile(this.url, function (data) {
  92885. _this.text = data;
  92886. onSuccess();
  92887. }, undefined, false, false, function (request, exception) {
  92888. if (request) {
  92889. onError(request.status + " " + request.statusText, exception);
  92890. }
  92891. });
  92892. };
  92893. return TextFileAssetTask;
  92894. }(AbstractAssetTask));
  92895. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92896. /**
  92897. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92898. */
  92899. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92900. __extends(BinaryFileAssetTask, _super);
  92901. /**
  92902. * Creates a new BinaryFileAssetTask object
  92903. * @param name defines the name of the new task
  92904. * @param url defines the location of the file to load
  92905. */
  92906. function BinaryFileAssetTask(
  92907. /**
  92908. * Defines the name of the task
  92909. */
  92910. name,
  92911. /**
  92912. * Defines the location of the file to load
  92913. */
  92914. url) {
  92915. var _this = _super.call(this, name) || this;
  92916. _this.name = name;
  92917. _this.url = url;
  92918. return _this;
  92919. }
  92920. /**
  92921. * Execute the current task
  92922. * @param scene defines the scene where you want your assets to be loaded
  92923. * @param onSuccess is a callback called when the task is successfully executed
  92924. * @param onError is a callback called if an error occurs
  92925. */
  92926. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92927. var _this = this;
  92928. scene._loadFile(this.url, function (data) {
  92929. _this.data = data;
  92930. onSuccess();
  92931. }, undefined, true, true, function (request, exception) {
  92932. if (request) {
  92933. onError(request.status + " " + request.statusText, exception);
  92934. }
  92935. });
  92936. };
  92937. return BinaryFileAssetTask;
  92938. }(AbstractAssetTask));
  92939. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92940. /**
  92941. * Define a task used by {BABYLON.AssetsManager} to load images
  92942. */
  92943. var ImageAssetTask = /** @class */ (function (_super) {
  92944. __extends(ImageAssetTask, _super);
  92945. /**
  92946. * Creates a new ImageAssetTask
  92947. * @param name defines the name of the task
  92948. * @param url defines the location of the image to load
  92949. */
  92950. function ImageAssetTask(
  92951. /**
  92952. * Defines the name of the task
  92953. */
  92954. name,
  92955. /**
  92956. * Defines the location of the image to load
  92957. */
  92958. url) {
  92959. var _this = _super.call(this, name) || this;
  92960. _this.name = name;
  92961. _this.url = url;
  92962. return _this;
  92963. }
  92964. /**
  92965. * Execute the current task
  92966. * @param scene defines the scene where you want your assets to be loaded
  92967. * @param onSuccess is a callback called when the task is successfully executed
  92968. * @param onError is a callback called if an error occurs
  92969. */
  92970. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92971. var _this = this;
  92972. var img = new Image();
  92973. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92974. img.onload = function () {
  92975. _this.image = img;
  92976. onSuccess();
  92977. };
  92978. img.onerror = function (err) {
  92979. onError("Error loading image", err);
  92980. };
  92981. img.src = this.url;
  92982. };
  92983. return ImageAssetTask;
  92984. }(AbstractAssetTask));
  92985. BABYLON.ImageAssetTask = ImageAssetTask;
  92986. /**
  92987. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92988. */
  92989. var TextureAssetTask = /** @class */ (function (_super) {
  92990. __extends(TextureAssetTask, _super);
  92991. /**
  92992. * Creates a new TextureAssetTask object
  92993. * @param name defines the name of the task
  92994. * @param url defines the location of the file to load
  92995. * @param noMipmap defines if mipmap should not be generated (default is false)
  92996. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92997. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92998. */
  92999. function TextureAssetTask(
  93000. /**
  93001. * Defines the name of the task
  93002. */
  93003. name,
  93004. /**
  93005. * Defines the location of the file to load
  93006. */
  93007. url,
  93008. /**
  93009. * Defines if mipmap should not be generated (default is false)
  93010. */
  93011. noMipmap,
  93012. /**
  93013. * Defines if texture must be inverted on Y axis (default is false)
  93014. */
  93015. invertY,
  93016. /**
  93017. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93018. */
  93019. samplingMode) {
  93020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93021. var _this = _super.call(this, name) || this;
  93022. _this.name = name;
  93023. _this.url = url;
  93024. _this.noMipmap = noMipmap;
  93025. _this.invertY = invertY;
  93026. _this.samplingMode = samplingMode;
  93027. return _this;
  93028. }
  93029. /**
  93030. * Execute the current task
  93031. * @param scene defines the scene where you want your assets to be loaded
  93032. * @param onSuccess is a callback called when the task is successfully executed
  93033. * @param onError is a callback called if an error occurs
  93034. */
  93035. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93036. var onload = function () {
  93037. onSuccess();
  93038. };
  93039. var onerror = function (message, exception) {
  93040. onError(message, exception);
  93041. };
  93042. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93043. };
  93044. return TextureAssetTask;
  93045. }(AbstractAssetTask));
  93046. BABYLON.TextureAssetTask = TextureAssetTask;
  93047. /**
  93048. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93049. */
  93050. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93051. __extends(CubeTextureAssetTask, _super);
  93052. /**
  93053. * Creates a new CubeTextureAssetTask
  93054. * @param name defines the name of the task
  93055. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93056. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93057. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93058. * @param files defines the explicit list of files (undefined by default)
  93059. */
  93060. function CubeTextureAssetTask(
  93061. /**
  93062. * Defines the name of the task
  93063. */
  93064. name,
  93065. /**
  93066. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93067. */
  93068. url,
  93069. /**
  93070. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93071. */
  93072. extensions,
  93073. /**
  93074. * Defines if mipmaps should not be generated (default is false)
  93075. */
  93076. noMipmap,
  93077. /**
  93078. * Defines the explicit list of files (undefined by default)
  93079. */
  93080. files) {
  93081. var _this = _super.call(this, name) || this;
  93082. _this.name = name;
  93083. _this.url = url;
  93084. _this.extensions = extensions;
  93085. _this.noMipmap = noMipmap;
  93086. _this.files = files;
  93087. return _this;
  93088. }
  93089. /**
  93090. * Execute the current task
  93091. * @param scene defines the scene where you want your assets to be loaded
  93092. * @param onSuccess is a callback called when the task is successfully executed
  93093. * @param onError is a callback called if an error occurs
  93094. */
  93095. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93096. var onload = function () {
  93097. onSuccess();
  93098. };
  93099. var onerror = function (message, exception) {
  93100. onError(message, exception);
  93101. };
  93102. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93103. };
  93104. return CubeTextureAssetTask;
  93105. }(AbstractAssetTask));
  93106. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93107. /**
  93108. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93109. */
  93110. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93111. __extends(HDRCubeTextureAssetTask, _super);
  93112. /**
  93113. * Creates a new HDRCubeTextureAssetTask object
  93114. * @param name defines the name of the task
  93115. * @param url defines the location of the file to load
  93116. * @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.
  93117. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93118. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93119. * @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)
  93120. * @param reserved Internal use only
  93121. */
  93122. function HDRCubeTextureAssetTask(
  93123. /**
  93124. * Defines the name of the task
  93125. */
  93126. name,
  93127. /**
  93128. * Defines the location of the file to load
  93129. */
  93130. url,
  93131. /**
  93132. * Defines the desired size (the more it increases the longer the generation will be)
  93133. */
  93134. size,
  93135. /**
  93136. * Defines if mipmaps should not be generated (default is false)
  93137. */
  93138. noMipmap,
  93139. /**
  93140. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93141. */
  93142. generateHarmonics,
  93143. /**
  93144. * 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)
  93145. */
  93146. gammaSpace,
  93147. /**
  93148. * Internal Use Only
  93149. */
  93150. reserved) {
  93151. if (noMipmap === void 0) { noMipmap = false; }
  93152. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93153. if (gammaSpace === void 0) { gammaSpace = false; }
  93154. if (reserved === void 0) { reserved = false; }
  93155. var _this = _super.call(this, name) || this;
  93156. _this.name = name;
  93157. _this.url = url;
  93158. _this.size = size;
  93159. _this.noMipmap = noMipmap;
  93160. _this.generateHarmonics = generateHarmonics;
  93161. _this.gammaSpace = gammaSpace;
  93162. _this.reserved = reserved;
  93163. return _this;
  93164. }
  93165. /**
  93166. * Execute the current task
  93167. * @param scene defines the scene where you want your assets to be loaded
  93168. * @param onSuccess is a callback called when the task is successfully executed
  93169. * @param onError is a callback called if an error occurs
  93170. */
  93171. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93172. var onload = function () {
  93173. onSuccess();
  93174. };
  93175. var onerror = function (message, exception) {
  93176. onError(message, exception);
  93177. };
  93178. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93179. };
  93180. return HDRCubeTextureAssetTask;
  93181. }(AbstractAssetTask));
  93182. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93183. /**
  93184. * This class can be used to easily import assets into a scene
  93185. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93186. */
  93187. var AssetsManager = /** @class */ (function () {
  93188. /**
  93189. * Creates a new AssetsManager
  93190. * @param scene defines the scene to work on
  93191. */
  93192. function AssetsManager(scene) {
  93193. this._isLoading = false;
  93194. this._tasks = new Array();
  93195. this._waitingTasksCount = 0;
  93196. this._totalTasksCount = 0;
  93197. /**
  93198. * Observable called when all tasks are processed
  93199. */
  93200. this.onTaskSuccessObservable = new BABYLON.Observable();
  93201. /**
  93202. * Observable called when a task had an error
  93203. */
  93204. this.onTaskErrorObservable = new BABYLON.Observable();
  93205. /**
  93206. * Observable called when a task is successful
  93207. */
  93208. this.onTasksDoneObservable = new BABYLON.Observable();
  93209. /**
  93210. * Observable called when a task is done (whatever the result is)
  93211. */
  93212. this.onProgressObservable = new BABYLON.Observable();
  93213. /**
  93214. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93215. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93216. */
  93217. this.useDefaultLoadingScreen = true;
  93218. this._scene = scene;
  93219. }
  93220. /**
  93221. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93222. * @param taskName defines the name of the new task
  93223. * @param meshesNames defines the name of meshes to load
  93224. * @param rootUrl defines the root url to use to locate files
  93225. * @param sceneFilename defines the filename of the scene file
  93226. * @returns a new {BABYLON.MeshAssetTask} object
  93227. */
  93228. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93229. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93230. this._tasks.push(task);
  93231. return task;
  93232. };
  93233. /**
  93234. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93235. * @param taskName defines the name of the new task
  93236. * @param url defines the url of the file to load
  93237. * @returns a new {BABYLON.TextFileAssetTask} object
  93238. */
  93239. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93240. var task = new TextFileAssetTask(taskName, url);
  93241. this._tasks.push(task);
  93242. return task;
  93243. };
  93244. /**
  93245. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93246. * @param taskName defines the name of the new task
  93247. * @param url defines the url of the file to load
  93248. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93249. */
  93250. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93251. var task = new BinaryFileAssetTask(taskName, url);
  93252. this._tasks.push(task);
  93253. return task;
  93254. };
  93255. /**
  93256. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93257. * @param taskName defines the name of the new task
  93258. * @param url defines the url of the file to load
  93259. * @returns a new {BABYLON.ImageAssetTask} object
  93260. */
  93261. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93262. var task = new ImageAssetTask(taskName, url);
  93263. this._tasks.push(task);
  93264. return task;
  93265. };
  93266. /**
  93267. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93268. * @param taskName defines the name of the new task
  93269. * @param url defines the url of the file to load
  93270. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93271. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93272. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93273. * @returns a new {BABYLON.TextureAssetTask} object
  93274. */
  93275. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93277. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93278. this._tasks.push(task);
  93279. return task;
  93280. };
  93281. /**
  93282. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93283. * @param taskName defines the name of the new task
  93284. * @param url defines the url of the file to load
  93285. * @param extensions defines the extension to use to load the cube map (can be null)
  93286. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93287. * @param files defines the list of files to load (can be null)
  93288. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93289. */
  93290. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93291. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93292. this._tasks.push(task);
  93293. return task;
  93294. };
  93295. /**
  93296. *
  93297. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93298. * @param taskName defines the name of the new task
  93299. * @param url defines the url of the file to load
  93300. * @param size defines the size you want for the cubemap (can be null)
  93301. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93302. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93303. * @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)
  93304. * @param reserved Internal use only
  93305. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93306. */
  93307. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93308. if (noMipmap === void 0) { noMipmap = false; }
  93309. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93310. if (gammaSpace === void 0) { gammaSpace = false; }
  93311. if (reserved === void 0) { reserved = false; }
  93312. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93313. this._tasks.push(task);
  93314. return task;
  93315. };
  93316. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93317. var _this = this;
  93318. this._waitingTasksCount--;
  93319. try {
  93320. if (task.taskState === AssetTaskState.DONE) {
  93321. // Let's remove successfull tasks
  93322. BABYLON.Tools.SetImmediate(function () {
  93323. var index = _this._tasks.indexOf(task);
  93324. if (index > -1) {
  93325. _this._tasks.splice(index, 1);
  93326. }
  93327. });
  93328. }
  93329. if (this.onProgress) {
  93330. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93331. }
  93332. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93333. }
  93334. catch (e) {
  93335. BABYLON.Tools.Error("Error running progress callbacks.");
  93336. console.log(e);
  93337. }
  93338. if (this._waitingTasksCount === 0) {
  93339. try {
  93340. if (this.onFinish) {
  93341. this.onFinish(this._tasks);
  93342. }
  93343. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93344. }
  93345. catch (e) {
  93346. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93347. console.log(e);
  93348. }
  93349. this._isLoading = false;
  93350. this._scene.getEngine().hideLoadingUI();
  93351. }
  93352. };
  93353. AssetsManager.prototype._runTask = function (task) {
  93354. var _this = this;
  93355. var done = function () {
  93356. try {
  93357. if (_this.onTaskSuccess) {
  93358. _this.onTaskSuccess(task);
  93359. }
  93360. _this.onTaskSuccessObservable.notifyObservers(task);
  93361. _this._decreaseWaitingTasksCount(task);
  93362. }
  93363. catch (e) {
  93364. error("Error executing task success callbacks", e);
  93365. }
  93366. };
  93367. var error = function (message, exception) {
  93368. task._setErrorObject(message, exception);
  93369. if (_this.onTaskError) {
  93370. _this.onTaskError(task);
  93371. }
  93372. _this.onTaskErrorObservable.notifyObservers(task);
  93373. _this._decreaseWaitingTasksCount(task);
  93374. };
  93375. task.run(this._scene, done, error);
  93376. };
  93377. /**
  93378. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93379. * @return the current instance of the {BABYLON.AssetsManager}
  93380. */
  93381. AssetsManager.prototype.reset = function () {
  93382. this._isLoading = false;
  93383. this._tasks = new Array();
  93384. return this;
  93385. };
  93386. /**
  93387. * Start the loading process
  93388. * @return the current instance of the {BABYLON.AssetsManager}
  93389. */
  93390. AssetsManager.prototype.load = function () {
  93391. if (this._isLoading) {
  93392. return this;
  93393. }
  93394. this._isLoading = true;
  93395. this._waitingTasksCount = this._tasks.length;
  93396. this._totalTasksCount = this._tasks.length;
  93397. if (this._waitingTasksCount === 0) {
  93398. this._isLoading = false;
  93399. if (this.onFinish) {
  93400. this.onFinish(this._tasks);
  93401. }
  93402. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93403. return this;
  93404. }
  93405. if (this.useDefaultLoadingScreen) {
  93406. this._scene.getEngine().displayLoadingUI();
  93407. }
  93408. for (var index = 0; index < this._tasks.length; index++) {
  93409. var task = this._tasks[index];
  93410. this._runTask(task);
  93411. }
  93412. return this;
  93413. };
  93414. return AssetsManager;
  93415. }());
  93416. BABYLON.AssetsManager = AssetsManager;
  93417. })(BABYLON || (BABYLON = {}));
  93418. //# sourceMappingURL=babylon.assetsManager.js.map
  93419. var BABYLON;
  93420. (function (BABYLON) {
  93421. var serializedGeometries = [];
  93422. var serializeGeometry = function (geometry, serializationGeometries) {
  93423. if (serializedGeometries[geometry.id]) {
  93424. return;
  93425. }
  93426. if (geometry.doNotSerialize) {
  93427. return;
  93428. }
  93429. if (geometry instanceof BABYLON.BoxGeometry) {
  93430. serializationGeometries.boxes.push(geometry.serialize());
  93431. }
  93432. else if (geometry instanceof BABYLON.SphereGeometry) {
  93433. serializationGeometries.spheres.push(geometry.serialize());
  93434. }
  93435. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93436. serializationGeometries.cylinders.push(geometry.serialize());
  93437. }
  93438. else if (geometry instanceof BABYLON.TorusGeometry) {
  93439. serializationGeometries.toruses.push(geometry.serialize());
  93440. }
  93441. else if (geometry instanceof BABYLON.GroundGeometry) {
  93442. serializationGeometries.grounds.push(geometry.serialize());
  93443. }
  93444. else if (geometry instanceof BABYLON.Plane) {
  93445. serializationGeometries.planes.push(geometry.serialize());
  93446. }
  93447. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93448. serializationGeometries.torusKnots.push(geometry.serialize());
  93449. }
  93450. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93451. throw new Error("Unknown primitive type");
  93452. }
  93453. else {
  93454. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93455. }
  93456. serializedGeometries[geometry.id] = true;
  93457. };
  93458. var serializeMesh = function (mesh, serializationScene) {
  93459. var serializationObject = {};
  93460. // Geometry
  93461. var geometry = mesh._geometry;
  93462. if (geometry) {
  93463. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93464. // 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
  93465. serializeGeometry(geometry, serializationScene.geometries);
  93466. }
  93467. }
  93468. // Custom
  93469. if (mesh.serialize) {
  93470. mesh.serialize(serializationObject);
  93471. }
  93472. return serializationObject;
  93473. };
  93474. var finalizeSingleMesh = function (mesh, serializationObject) {
  93475. //only works if the mesh is already loaded
  93476. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93477. //serialize material
  93478. if (mesh.material) {
  93479. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93480. serializationObject.materials = serializationObject.materials || [];
  93481. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93482. serializationObject.materials.push(mesh.material.serialize());
  93483. }
  93484. }
  93485. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93486. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93487. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93488. serializationObject.multiMaterials.push(mesh.material.serialize());
  93489. }
  93490. }
  93491. }
  93492. //serialize geometry
  93493. var geometry = mesh._geometry;
  93494. if (geometry) {
  93495. if (!serializationObject.geometries) {
  93496. serializationObject.geometries = {};
  93497. serializationObject.geometries.boxes = [];
  93498. serializationObject.geometries.spheres = [];
  93499. serializationObject.geometries.cylinders = [];
  93500. serializationObject.geometries.toruses = [];
  93501. serializationObject.geometries.grounds = [];
  93502. serializationObject.geometries.planes = [];
  93503. serializationObject.geometries.torusKnots = [];
  93504. serializationObject.geometries.vertexData = [];
  93505. }
  93506. serializeGeometry(geometry, serializationObject.geometries);
  93507. }
  93508. // Skeletons
  93509. if (mesh.skeleton) {
  93510. serializationObject.skeletons = serializationObject.skeletons || [];
  93511. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93512. }
  93513. //serialize the actual mesh
  93514. serializationObject.meshes = serializationObject.meshes || [];
  93515. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93516. }
  93517. };
  93518. var SceneSerializer = /** @class */ (function () {
  93519. function SceneSerializer() {
  93520. }
  93521. SceneSerializer.ClearCache = function () {
  93522. serializedGeometries = [];
  93523. };
  93524. SceneSerializer.Serialize = function (scene) {
  93525. var serializationObject = {};
  93526. SceneSerializer.ClearCache();
  93527. // Scene
  93528. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93529. serializationObject.autoClear = scene.autoClear;
  93530. serializationObject.clearColor = scene.clearColor.asArray();
  93531. serializationObject.ambientColor = scene.ambientColor.asArray();
  93532. serializationObject.gravity = scene.gravity.asArray();
  93533. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93534. serializationObject.workerCollisions = scene.workerCollisions;
  93535. // Fog
  93536. if (scene.fogMode && scene.fogMode !== 0) {
  93537. serializationObject.fogMode = scene.fogMode;
  93538. serializationObject.fogColor = scene.fogColor.asArray();
  93539. serializationObject.fogStart = scene.fogStart;
  93540. serializationObject.fogEnd = scene.fogEnd;
  93541. serializationObject.fogDensity = scene.fogDensity;
  93542. }
  93543. //Physics
  93544. if (scene.isPhysicsEnabled()) {
  93545. var physicEngine = scene.getPhysicsEngine();
  93546. if (physicEngine) {
  93547. serializationObject.physicsEnabled = true;
  93548. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93549. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93550. }
  93551. }
  93552. // Metadata
  93553. if (scene.metadata) {
  93554. serializationObject.metadata = scene.metadata;
  93555. }
  93556. // Morph targets
  93557. serializationObject.morphTargetManagers = [];
  93558. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93559. var abstractMesh = _a[_i];
  93560. var manager = abstractMesh.morphTargetManager;
  93561. if (manager) {
  93562. serializationObject.morphTargetManagers.push(manager.serialize());
  93563. }
  93564. }
  93565. // Lights
  93566. serializationObject.lights = [];
  93567. var index;
  93568. var light;
  93569. for (index = 0; index < scene.lights.length; index++) {
  93570. light = scene.lights[index];
  93571. if (!light.doNotSerialize) {
  93572. serializationObject.lights.push(light.serialize());
  93573. }
  93574. }
  93575. // Cameras
  93576. serializationObject.cameras = [];
  93577. for (index = 0; index < scene.cameras.length; index++) {
  93578. var camera = scene.cameras[index];
  93579. if (!camera.doNotSerialize) {
  93580. serializationObject.cameras.push(camera.serialize());
  93581. }
  93582. }
  93583. if (scene.activeCamera) {
  93584. serializationObject.activeCameraID = scene.activeCamera.id;
  93585. }
  93586. // Animations
  93587. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93588. // Materials
  93589. serializationObject.materials = [];
  93590. serializationObject.multiMaterials = [];
  93591. var material;
  93592. for (index = 0; index < scene.materials.length; index++) {
  93593. material = scene.materials[index];
  93594. if (!material.doNotSerialize) {
  93595. serializationObject.materials.push(material.serialize());
  93596. }
  93597. }
  93598. // MultiMaterials
  93599. serializationObject.multiMaterials = [];
  93600. for (index = 0; index < scene.multiMaterials.length; index++) {
  93601. var multiMaterial = scene.multiMaterials[index];
  93602. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93603. }
  93604. // Environment texture
  93605. if (scene.environmentTexture) {
  93606. serializationObject.environmentTexture = scene.environmentTexture.name;
  93607. }
  93608. // Skeletons
  93609. serializationObject.skeletons = [];
  93610. for (index = 0; index < scene.skeletons.length; index++) {
  93611. var skeleton = scene.skeletons[index];
  93612. if (!skeleton.doNotSerialize) {
  93613. serializationObject.skeletons.push(skeleton.serialize());
  93614. }
  93615. }
  93616. // Transform nodes
  93617. serializationObject.transformNodes = [];
  93618. for (index = 0; index < scene.transformNodes.length; index++) {
  93619. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93620. }
  93621. // Geometries
  93622. serializationObject.geometries = {};
  93623. serializationObject.geometries.boxes = [];
  93624. serializationObject.geometries.spheres = [];
  93625. serializationObject.geometries.cylinders = [];
  93626. serializationObject.geometries.toruses = [];
  93627. serializationObject.geometries.grounds = [];
  93628. serializationObject.geometries.planes = [];
  93629. serializationObject.geometries.torusKnots = [];
  93630. serializationObject.geometries.vertexData = [];
  93631. serializedGeometries = [];
  93632. var geometries = scene.getGeometries();
  93633. for (index = 0; index < geometries.length; index++) {
  93634. var geometry = geometries[index];
  93635. if (geometry.isReady()) {
  93636. serializeGeometry(geometry, serializationObject.geometries);
  93637. }
  93638. }
  93639. // Meshes
  93640. serializationObject.meshes = [];
  93641. for (index = 0; index < scene.meshes.length; index++) {
  93642. var abstractMesh = scene.meshes[index];
  93643. if (abstractMesh instanceof BABYLON.Mesh) {
  93644. var mesh = abstractMesh;
  93645. if (!mesh.doNotSerialize) {
  93646. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93647. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93648. }
  93649. }
  93650. }
  93651. }
  93652. // Particles Systems
  93653. serializationObject.particleSystems = [];
  93654. for (index = 0; index < scene.particleSystems.length; index++) {
  93655. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93656. }
  93657. // Lens flares
  93658. serializationObject.lensFlareSystems = [];
  93659. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93660. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93661. }
  93662. // Shadows
  93663. serializationObject.shadowGenerators = [];
  93664. for (index = 0; index < scene.lights.length; index++) {
  93665. light = scene.lights[index];
  93666. var shadowGenerator = light.getShadowGenerator();
  93667. if (shadowGenerator) {
  93668. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93669. }
  93670. }
  93671. // Action Manager
  93672. if (scene.actionManager) {
  93673. serializationObject.actions = scene.actionManager.serialize("scene");
  93674. }
  93675. // Audio
  93676. serializationObject.sounds = [];
  93677. for (index = 0; index < scene.soundTracks.length; index++) {
  93678. var soundtrack = scene.soundTracks[index];
  93679. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93680. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93681. }
  93682. }
  93683. // Effect layers
  93684. serializationObject.effectLayers = [];
  93685. for (index = 0; index < scene.effectLayers.length; index++) {
  93686. var layer = scene.effectLayers[index];
  93687. if (layer.serialize) {
  93688. serializationObject.effectLayers.push(layer.serialize());
  93689. }
  93690. }
  93691. return serializationObject;
  93692. };
  93693. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93694. if (withParents === void 0) { withParents = false; }
  93695. if (withChildren === void 0) { withChildren = false; }
  93696. var serializationObject = {};
  93697. SceneSerializer.ClearCache();
  93698. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93699. if (withParents || withChildren) {
  93700. //deliberate for loop! not for each, appended should be processed as well.
  93701. for (var i = 0; i < toSerialize.length; ++i) {
  93702. if (withChildren) {
  93703. toSerialize[i].getDescendants().forEach(function (node) {
  93704. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93705. toSerialize.push(node);
  93706. }
  93707. });
  93708. }
  93709. //make sure the array doesn't contain the object already
  93710. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93711. toSerialize.push(toSerialize[i].parent);
  93712. }
  93713. }
  93714. }
  93715. toSerialize.forEach(function (mesh) {
  93716. finalizeSingleMesh(mesh, serializationObject);
  93717. });
  93718. return serializationObject;
  93719. };
  93720. return SceneSerializer;
  93721. }());
  93722. BABYLON.SceneSerializer = SceneSerializer;
  93723. })(BABYLON || (BABYLON = {}));
  93724. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93725. var BABYLON;
  93726. (function (BABYLON) {
  93727. var ReflectionProbe = /** @class */ (function () {
  93728. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93729. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93730. var _this = this;
  93731. this.name = name;
  93732. this._viewMatrix = BABYLON.Matrix.Identity();
  93733. this._target = BABYLON.Vector3.Zero();
  93734. this._add = BABYLON.Vector3.Zero();
  93735. this._invertYAxis = false;
  93736. this.position = BABYLON.Vector3.Zero();
  93737. this._scene = scene;
  93738. this._scene.reflectionProbes.push(this);
  93739. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93740. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93741. switch (faceIndex) {
  93742. case 0:
  93743. _this._add.copyFromFloats(1, 0, 0);
  93744. break;
  93745. case 1:
  93746. _this._add.copyFromFloats(-1, 0, 0);
  93747. break;
  93748. case 2:
  93749. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93750. break;
  93751. case 3:
  93752. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93753. break;
  93754. case 4:
  93755. _this._add.copyFromFloats(0, 0, 1);
  93756. break;
  93757. case 5:
  93758. _this._add.copyFromFloats(0, 0, -1);
  93759. break;
  93760. }
  93761. if (_this._attachedMesh) {
  93762. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93763. }
  93764. _this.position.addToRef(_this._add, _this._target);
  93765. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93766. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93767. scene._forcedViewPosition = _this.position;
  93768. });
  93769. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93770. scene._forcedViewPosition = null;
  93771. scene.updateTransformMatrix(true);
  93772. });
  93773. if (scene.activeCamera) {
  93774. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93775. }
  93776. }
  93777. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93778. get: function () {
  93779. return this._renderTargetTexture.samples;
  93780. },
  93781. set: function (value) {
  93782. this._renderTargetTexture.samples = value;
  93783. },
  93784. enumerable: true,
  93785. configurable: true
  93786. });
  93787. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93788. get: function () {
  93789. return this._renderTargetTexture.refreshRate;
  93790. },
  93791. set: function (value) {
  93792. this._renderTargetTexture.refreshRate = value;
  93793. },
  93794. enumerable: true,
  93795. configurable: true
  93796. });
  93797. ReflectionProbe.prototype.getScene = function () {
  93798. return this._scene;
  93799. };
  93800. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93801. get: function () {
  93802. return this._renderTargetTexture;
  93803. },
  93804. enumerable: true,
  93805. configurable: true
  93806. });
  93807. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93808. get: function () {
  93809. return this._renderTargetTexture.renderList;
  93810. },
  93811. enumerable: true,
  93812. configurable: true
  93813. });
  93814. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93815. this._attachedMesh = mesh;
  93816. };
  93817. /**
  93818. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93819. *
  93820. * @param renderingGroupId The rendering group id corresponding to its index
  93821. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93822. */
  93823. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93824. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93825. };
  93826. ReflectionProbe.prototype.dispose = function () {
  93827. var index = this._scene.reflectionProbes.indexOf(this);
  93828. if (index !== -1) {
  93829. // Remove from the scene if found
  93830. this._scene.reflectionProbes.splice(index, 1);
  93831. }
  93832. if (this._renderTargetTexture) {
  93833. this._renderTargetTexture.dispose();
  93834. this._renderTargetTexture = null;
  93835. }
  93836. };
  93837. return ReflectionProbe;
  93838. }());
  93839. BABYLON.ReflectionProbe = ReflectionProbe;
  93840. })(BABYLON || (BABYLON = {}));
  93841. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93842. var BABYLON;
  93843. (function (BABYLON) {
  93844. var Layer = /** @class */ (function () {
  93845. function Layer(name, imgUrl, scene, isBackground, color) {
  93846. this.name = name;
  93847. this.scale = new BABYLON.Vector2(1, 1);
  93848. this.offset = new BABYLON.Vector2(0, 0);
  93849. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93850. this.layerMask = 0x0FFFFFFF;
  93851. this._vertexBuffers = {};
  93852. // Events
  93853. /**
  93854. * An event triggered when the layer is disposed.
  93855. */
  93856. this.onDisposeObservable = new BABYLON.Observable();
  93857. /**
  93858. * An event triggered before rendering the scene
  93859. */
  93860. this.onBeforeRenderObservable = new BABYLON.Observable();
  93861. /**
  93862. * An event triggered after rendering the scene
  93863. */
  93864. this.onAfterRenderObservable = new BABYLON.Observable();
  93865. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93866. this.isBackground = isBackground === undefined ? true : isBackground;
  93867. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93868. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93869. this._scene.layers.push(this);
  93870. var engine = this._scene.getEngine();
  93871. // VBO
  93872. var vertices = [];
  93873. vertices.push(1, 1);
  93874. vertices.push(-1, 1);
  93875. vertices.push(-1, -1);
  93876. vertices.push(1, -1);
  93877. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93879. this._createIndexBuffer();
  93880. // Effects
  93881. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93882. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93883. }
  93884. Object.defineProperty(Layer.prototype, "onDispose", {
  93885. set: function (callback) {
  93886. if (this._onDisposeObserver) {
  93887. this.onDisposeObservable.remove(this._onDisposeObserver);
  93888. }
  93889. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93890. },
  93891. enumerable: true,
  93892. configurable: true
  93893. });
  93894. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93895. set: function (callback) {
  93896. if (this._onBeforeRenderObserver) {
  93897. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93898. }
  93899. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93900. },
  93901. enumerable: true,
  93902. configurable: true
  93903. });
  93904. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93905. set: function (callback) {
  93906. if (this._onAfterRenderObserver) {
  93907. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93908. }
  93909. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93910. },
  93911. enumerable: true,
  93912. configurable: true
  93913. });
  93914. Layer.prototype._createIndexBuffer = function () {
  93915. var engine = this._scene.getEngine();
  93916. // Indices
  93917. var indices = [];
  93918. indices.push(0);
  93919. indices.push(1);
  93920. indices.push(2);
  93921. indices.push(0);
  93922. indices.push(2);
  93923. indices.push(3);
  93924. this._indexBuffer = engine.createIndexBuffer(indices);
  93925. };
  93926. Layer.prototype._rebuild = function () {
  93927. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93928. if (vb) {
  93929. vb._rebuild();
  93930. }
  93931. this._createIndexBuffer();
  93932. };
  93933. Layer.prototype.render = function () {
  93934. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93935. // Check
  93936. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93937. return;
  93938. var engine = this._scene.getEngine();
  93939. this.onBeforeRenderObservable.notifyObservers(this);
  93940. // Render
  93941. engine.enableEffect(currentEffect);
  93942. engine.setState(false);
  93943. // Texture
  93944. currentEffect.setTexture("textureSampler", this.texture);
  93945. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93946. // Color
  93947. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93948. // Scale / offset
  93949. currentEffect.setVector2("offset", this.offset);
  93950. currentEffect.setVector2("scale", this.scale);
  93951. // VBOs
  93952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93953. // Draw order
  93954. if (!this.alphaTest) {
  93955. engine.setAlphaMode(this.alphaBlendingMode);
  93956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93957. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93958. }
  93959. else {
  93960. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93961. }
  93962. this.onAfterRenderObservable.notifyObservers(this);
  93963. };
  93964. Layer.prototype.dispose = function () {
  93965. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93966. if (vertexBuffer) {
  93967. vertexBuffer.dispose();
  93968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93969. }
  93970. if (this._indexBuffer) {
  93971. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93972. this._indexBuffer = null;
  93973. }
  93974. if (this.texture) {
  93975. this.texture.dispose();
  93976. this.texture = null;
  93977. }
  93978. // Remove from scene
  93979. var index = this._scene.layers.indexOf(this);
  93980. this._scene.layers.splice(index, 1);
  93981. // Callback
  93982. this.onDisposeObservable.notifyObservers(this);
  93983. this.onDisposeObservable.clear();
  93984. this.onAfterRenderObservable.clear();
  93985. this.onBeforeRenderObservable.clear();
  93986. };
  93987. return Layer;
  93988. }());
  93989. BABYLON.Layer = Layer;
  93990. })(BABYLON || (BABYLON = {}));
  93991. //# sourceMappingURL=babylon.layer.js.map
  93992. var BABYLON;
  93993. (function (BABYLON) {
  93994. var TextureTools = /** @class */ (function () {
  93995. function TextureTools() {
  93996. }
  93997. /**
  93998. * Uses the GPU to create a copy texture rescaled at a given size
  93999. * @param texture Texture to copy from
  94000. * @param width Desired width
  94001. * @param height Desired height
  94002. * @return Generated texture
  94003. */
  94004. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94005. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94006. var scene = texture.getScene();
  94007. var engine = scene.getEngine();
  94008. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94009. rtt.wrapU = texture.wrapU;
  94010. rtt.wrapV = texture.wrapV;
  94011. rtt.uOffset = texture.uOffset;
  94012. rtt.vOffset = texture.vOffset;
  94013. rtt.uScale = texture.uScale;
  94014. rtt.vScale = texture.vScale;
  94015. rtt.uAng = texture.uAng;
  94016. rtt.vAng = texture.vAng;
  94017. rtt.wAng = texture.wAng;
  94018. rtt.coordinatesIndex = texture.coordinatesIndex;
  94019. rtt.level = texture.level;
  94020. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94021. rtt._texture.isReady = false;
  94022. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94023. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94024. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94025. passPostProcess.getEffect().executeWhenCompiled(function () {
  94026. passPostProcess.onApply = function (effect) {
  94027. effect.setTexture("textureSampler", texture);
  94028. };
  94029. var internalTexture = rtt.getInternalTexture();
  94030. if (internalTexture) {
  94031. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94032. engine.unBindFramebuffer(internalTexture);
  94033. rtt.disposeFramebufferObjects();
  94034. passPostProcess.dispose();
  94035. internalTexture.isReady = true;
  94036. }
  94037. });
  94038. return rtt;
  94039. };
  94040. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94041. if (!scene._environmentBRDFTexture) {
  94042. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94043. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94044. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94045. scene._environmentBRDFTexture = texture;
  94046. }
  94047. return scene._environmentBRDFTexture;
  94048. };
  94049. 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=";
  94050. return TextureTools;
  94051. }());
  94052. BABYLON.TextureTools = TextureTools;
  94053. })(BABYLON || (BABYLON = {}));
  94054. //# sourceMappingURL=babylon.textureTools.js.map
  94055. var BABYLON;
  94056. (function (BABYLON) {
  94057. var FramingBehavior = /** @class */ (function () {
  94058. function FramingBehavior() {
  94059. this._mode = FramingBehavior.FitFrustumSidesMode;
  94060. this._radiusScale = 1.0;
  94061. this._positionScale = 0.5;
  94062. this._defaultElevation = 0.3;
  94063. this._elevationReturnTime = 1500;
  94064. this._elevationReturnWaitTime = 1000;
  94065. this._zoomStopsAnimation = false;
  94066. this._framingTime = 1500;
  94067. this._isPointerDown = false;
  94068. this._lastInteractionTime = -Infinity;
  94069. // Framing control
  94070. this._animatables = new Array();
  94071. this._betaIsAnimating = false;
  94072. }
  94073. Object.defineProperty(FramingBehavior.prototype, "name", {
  94074. get: function () {
  94075. return "Framing";
  94076. },
  94077. enumerable: true,
  94078. configurable: true
  94079. });
  94080. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94081. /**
  94082. * Gets current mode used by the behavior.
  94083. */
  94084. get: function () {
  94085. return this._mode;
  94086. },
  94087. /**
  94088. * Sets the current mode used by the behavior
  94089. */
  94090. set: function (mode) {
  94091. this._mode = mode;
  94092. },
  94093. enumerable: true,
  94094. configurable: true
  94095. });
  94096. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94097. /**
  94098. * Gets the scale applied to the radius
  94099. */
  94100. get: function () {
  94101. return this._radiusScale;
  94102. },
  94103. /**
  94104. * Sets the scale applied to the radius (1 by default)
  94105. */
  94106. set: function (radius) {
  94107. this._radiusScale = radius;
  94108. },
  94109. enumerable: true,
  94110. configurable: true
  94111. });
  94112. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94113. /**
  94114. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94115. */
  94116. get: function () {
  94117. return this._positionScale;
  94118. },
  94119. /**
  94120. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94121. */
  94122. set: function (scale) {
  94123. this._positionScale = scale;
  94124. },
  94125. enumerable: true,
  94126. configurable: true
  94127. });
  94128. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94129. /**
  94130. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94131. * behaviour is triggered, in radians.
  94132. */
  94133. get: function () {
  94134. return this._defaultElevation;
  94135. },
  94136. /**
  94137. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94138. * behaviour is triggered, in radians.
  94139. */
  94140. set: function (elevation) {
  94141. this._defaultElevation = elevation;
  94142. },
  94143. enumerable: true,
  94144. configurable: true
  94145. });
  94146. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94147. /**
  94148. * Gets the time (in milliseconds) taken to return to the default beta position.
  94149. * Negative value indicates camera should not return to default.
  94150. */
  94151. get: function () {
  94152. return this._elevationReturnTime;
  94153. },
  94154. /**
  94155. * Sets the time (in milliseconds) taken to return to the default beta position.
  94156. * Negative value indicates camera should not return to default.
  94157. */
  94158. set: function (speed) {
  94159. this._elevationReturnTime = speed;
  94160. },
  94161. enumerable: true,
  94162. configurable: true
  94163. });
  94164. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94165. /**
  94166. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94167. */
  94168. get: function () {
  94169. return this._elevationReturnWaitTime;
  94170. },
  94171. /**
  94172. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94173. */
  94174. set: function (time) {
  94175. this._elevationReturnWaitTime = time;
  94176. },
  94177. enumerable: true,
  94178. configurable: true
  94179. });
  94180. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94181. /**
  94182. * Gets the flag that indicates if user zooming should stop animation.
  94183. */
  94184. get: function () {
  94185. return this._zoomStopsAnimation;
  94186. },
  94187. /**
  94188. * Sets the flag that indicates if user zooming should stop animation.
  94189. */
  94190. set: function (flag) {
  94191. this._zoomStopsAnimation = flag;
  94192. },
  94193. enumerable: true,
  94194. configurable: true
  94195. });
  94196. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94197. /**
  94198. * Gets the transition time when framing the mesh, in milliseconds
  94199. */
  94200. get: function () {
  94201. return this._framingTime;
  94202. },
  94203. /**
  94204. * Sets the transition time when framing the mesh, in milliseconds
  94205. */
  94206. set: function (time) {
  94207. this._framingTime = time;
  94208. },
  94209. enumerable: true,
  94210. configurable: true
  94211. });
  94212. FramingBehavior.prototype.init = function () {
  94213. // Do notihng
  94214. };
  94215. FramingBehavior.prototype.attach = function (camera) {
  94216. var _this = this;
  94217. this._attachedCamera = camera;
  94218. var scene = this._attachedCamera.getScene();
  94219. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94220. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94221. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94222. _this._isPointerDown = true;
  94223. return;
  94224. }
  94225. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94226. _this._isPointerDown = false;
  94227. }
  94228. });
  94229. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94230. if (mesh) {
  94231. _this.zoomOnMesh(mesh);
  94232. }
  94233. });
  94234. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94235. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94236. _this._applyUserInteraction();
  94237. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94238. // back to the default position after a given timeout
  94239. _this._maintainCameraAboveGround();
  94240. });
  94241. };
  94242. FramingBehavior.prototype.detach = function () {
  94243. if (!this._attachedCamera) {
  94244. return;
  94245. }
  94246. var scene = this._attachedCamera.getScene();
  94247. if (this._onPrePointerObservableObserver) {
  94248. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94249. }
  94250. if (this._onAfterCheckInputsObserver) {
  94251. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94252. }
  94253. if (this._onMeshTargetChangedObserver) {
  94254. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94255. }
  94256. this._attachedCamera = null;
  94257. };
  94258. /**
  94259. * Targets the given mesh and updates zoom level accordingly.
  94260. * @param mesh The mesh to target.
  94261. * @param radius Optional. If a cached radius position already exists, overrides default.
  94262. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94263. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94264. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94265. */
  94266. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94267. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94268. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94269. mesh.computeWorldMatrix(true);
  94270. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94271. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94272. };
  94273. /**
  94274. * Targets the given mesh with its children and updates zoom level accordingly.
  94275. * @param mesh The mesh to target.
  94276. * @param radius Optional. If a cached radius position already exists, overrides default.
  94277. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94278. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94279. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94280. */
  94281. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94282. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94283. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94284. mesh.computeWorldMatrix(true);
  94285. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94286. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94287. };
  94288. /**
  94289. * Targets the given meshes with their children and updates zoom level accordingly.
  94290. * @param meshes The mesh to target.
  94291. * @param radius Optional. If a cached radius position already exists, overrides default.
  94292. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94293. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94294. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94295. */
  94296. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94297. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94298. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94299. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94300. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94301. for (var i = 0; i < meshes.length; i++) {
  94302. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94303. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94304. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94305. }
  94306. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94307. };
  94308. /**
  94309. * Targets the given mesh and updates zoom level accordingly.
  94310. * @param mesh The mesh to target.
  94311. * @param radius Optional. If a cached radius position already exists, overrides default.
  94312. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94313. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94314. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94315. */
  94316. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94317. var _this = this;
  94318. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94319. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94320. var zoomTarget;
  94321. if (!this._attachedCamera) {
  94322. return;
  94323. }
  94324. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94325. var bottom = minimumWorld.y;
  94326. var top = maximumWorld.y;
  94327. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94328. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94329. if (focusOnOriginXZ) {
  94330. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94331. }
  94332. else {
  94333. var centerWorld = minimumWorld.add(radiusWorld);
  94334. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94335. }
  94336. if (!this._vectorTransition) {
  94337. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94338. }
  94339. this._betaIsAnimating = true;
  94340. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94341. if (animatable) {
  94342. this._animatables.push(animatable);
  94343. }
  94344. // sets the radius and lower radius bounds
  94345. // Small delta ensures camera is not always at lower zoom limit.
  94346. var radius = 0;
  94347. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94348. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94349. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94350. radius = position;
  94351. }
  94352. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94353. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94354. if (this._attachedCamera.lowerRadiusLimit === null) {
  94355. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94356. }
  94357. }
  94358. // Set sensibilities
  94359. var extend = maximumWorld.subtract(minimumWorld).length();
  94360. this._attachedCamera.panningSensibility = 5000 / extend;
  94361. this._attachedCamera.wheelPrecision = 100 / radius;
  94362. // transition to new radius
  94363. if (!this._radiusTransition) {
  94364. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94365. }
  94366. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94367. _this.stopAllAnimations();
  94368. if (onAnimationEnd) {
  94369. onAnimationEnd();
  94370. }
  94371. if (_this._attachedCamera) {
  94372. _this._attachedCamera.storeState();
  94373. }
  94374. });
  94375. if (animatable) {
  94376. this._animatables.push(animatable);
  94377. }
  94378. };
  94379. /**
  94380. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94381. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94382. * frustum width.
  94383. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94384. * to fully enclose the mesh in the viewing frustum.
  94385. */
  94386. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94387. var size = maximumWorld.subtract(minimumWorld);
  94388. var boxVectorGlobalDiagonal = size.length();
  94389. var frustumSlope = this._getFrustumSlope();
  94390. // Formula for setting distance
  94391. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94392. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94393. // Horizon distance
  94394. var radius = radiusWithoutFraming * this._radiusScale;
  94395. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94396. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94397. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94398. var camera = this._attachedCamera;
  94399. if (!camera) {
  94400. return 0;
  94401. }
  94402. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94403. // Don't exceed the requested limit
  94404. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94405. }
  94406. // Don't exceed the upper radius limit
  94407. if (camera.upperRadiusLimit) {
  94408. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94409. }
  94410. return distance;
  94411. };
  94412. /**
  94413. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94414. * is automatically returned to its default position (expected to be above ground plane).
  94415. */
  94416. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94417. var _this = this;
  94418. if (this._elevationReturnTime < 0) {
  94419. return;
  94420. }
  94421. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94422. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94423. var limitBeta = Math.PI * 0.5;
  94424. // Bring the camera back up if below the ground plane
  94425. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94426. this._betaIsAnimating = true;
  94427. //Transition to new position
  94428. this.stopAllAnimations();
  94429. if (!this._betaTransition) {
  94430. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94431. }
  94432. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94433. _this._clearAnimationLocks();
  94434. _this.stopAllAnimations();
  94435. });
  94436. if (animatabe) {
  94437. this._animatables.push(animatabe);
  94438. }
  94439. }
  94440. };
  94441. /**
  94442. * Returns the frustum slope based on the canvas ratio and camera FOV
  94443. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94444. */
  94445. FramingBehavior.prototype._getFrustumSlope = function () {
  94446. // Calculate the viewport ratio
  94447. // Aspect Ratio is Height/Width.
  94448. var camera = this._attachedCamera;
  94449. if (!camera) {
  94450. return BABYLON.Vector2.Zero();
  94451. }
  94452. var engine = camera.getScene().getEngine();
  94453. var aspectRatio = engine.getAspectRatio(camera);
  94454. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94455. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94456. var frustumSlopeY = Math.tan(camera.fov / 2);
  94457. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94458. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94459. // along the forward vector.
  94460. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94461. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94462. };
  94463. /**
  94464. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94465. */
  94466. FramingBehavior.prototype._clearAnimationLocks = function () {
  94467. this._betaIsAnimating = false;
  94468. };
  94469. /**
  94470. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94471. */
  94472. FramingBehavior.prototype._applyUserInteraction = function () {
  94473. if (this.isUserIsMoving) {
  94474. this._lastInteractionTime = BABYLON.Tools.Now;
  94475. this.stopAllAnimations();
  94476. this._clearAnimationLocks();
  94477. }
  94478. };
  94479. /**
  94480. * Stops and removes all animations that have been applied to the camera
  94481. */
  94482. FramingBehavior.prototype.stopAllAnimations = function () {
  94483. if (this._attachedCamera) {
  94484. this._attachedCamera.animations = [];
  94485. }
  94486. while (this._animatables.length) {
  94487. if (this._animatables[0]) {
  94488. this._animatables[0].onAnimationEnd = null;
  94489. this._animatables[0].stop();
  94490. }
  94491. this._animatables.shift();
  94492. }
  94493. };
  94494. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94495. /**
  94496. * Gets a value indicating if the user is moving the camera
  94497. */
  94498. get: function () {
  94499. if (!this._attachedCamera) {
  94500. return false;
  94501. }
  94502. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94503. this._attachedCamera.inertialBetaOffset !== 0 ||
  94504. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94505. this._attachedCamera.inertialPanningX !== 0 ||
  94506. this._attachedCamera.inertialPanningY !== 0 ||
  94507. this._isPointerDown;
  94508. },
  94509. enumerable: true,
  94510. configurable: true
  94511. });
  94512. /**
  94513. * The easing function used by animations
  94514. */
  94515. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94516. /**
  94517. * The easing mode used by animations
  94518. */
  94519. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94520. // Statics
  94521. /**
  94522. * The camera can move all the way towards the mesh.
  94523. */
  94524. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94525. /**
  94526. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94527. */
  94528. FramingBehavior.FitFrustumSidesMode = 1;
  94529. return FramingBehavior;
  94530. }());
  94531. BABYLON.FramingBehavior = FramingBehavior;
  94532. })(BABYLON || (BABYLON = {}));
  94533. //# sourceMappingURL=babylon.framingBehavior.js.map
  94534. var BABYLON;
  94535. (function (BABYLON) {
  94536. /**
  94537. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94538. */
  94539. var BouncingBehavior = /** @class */ (function () {
  94540. function BouncingBehavior() {
  94541. /**
  94542. * The duration of the animation, in milliseconds
  94543. */
  94544. this.transitionDuration = 450;
  94545. /**
  94546. * Length of the distance animated by the transition when lower radius is reached
  94547. */
  94548. this.lowerRadiusTransitionRange = 2;
  94549. /**
  94550. * Length of the distance animated by the transition when upper radius is reached
  94551. */
  94552. this.upperRadiusTransitionRange = -2;
  94553. this._autoTransitionRange = false;
  94554. // Animations
  94555. this._radiusIsAnimating = false;
  94556. this._radiusBounceTransition = null;
  94557. this._animatables = new Array();
  94558. }
  94559. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94560. get: function () {
  94561. return "Bouncing";
  94562. },
  94563. enumerable: true,
  94564. configurable: true
  94565. });
  94566. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94567. /**
  94568. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94569. */
  94570. get: function () {
  94571. return this._autoTransitionRange;
  94572. },
  94573. /**
  94574. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94575. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94576. */
  94577. set: function (value) {
  94578. var _this = this;
  94579. if (this._autoTransitionRange === value) {
  94580. return;
  94581. }
  94582. this._autoTransitionRange = value;
  94583. var camera = this._attachedCamera;
  94584. if (!camera) {
  94585. return;
  94586. }
  94587. if (value) {
  94588. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94589. if (!mesh) {
  94590. return;
  94591. }
  94592. mesh.computeWorldMatrix(true);
  94593. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94594. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94595. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94596. });
  94597. }
  94598. else if (this._onMeshTargetChangedObserver) {
  94599. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94600. }
  94601. },
  94602. enumerable: true,
  94603. configurable: true
  94604. });
  94605. BouncingBehavior.prototype.init = function () {
  94606. // Do notihng
  94607. };
  94608. BouncingBehavior.prototype.attach = function (camera) {
  94609. var _this = this;
  94610. this._attachedCamera = camera;
  94611. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94612. if (!_this._attachedCamera) {
  94613. return;
  94614. }
  94615. // Add the bounce animation to the lower radius limit
  94616. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94617. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94618. }
  94619. // Add the bounce animation to the upper radius limit
  94620. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94621. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94622. }
  94623. });
  94624. };
  94625. BouncingBehavior.prototype.detach = function () {
  94626. if (!this._attachedCamera) {
  94627. return;
  94628. }
  94629. if (this._onAfterCheckInputsObserver) {
  94630. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94631. }
  94632. if (this._onMeshTargetChangedObserver) {
  94633. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94634. }
  94635. this._attachedCamera = null;
  94636. };
  94637. /**
  94638. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94639. * @param radiusLimit The limit to check against.
  94640. * @return Bool to indicate if at limit.
  94641. */
  94642. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94643. if (!this._attachedCamera) {
  94644. return false;
  94645. }
  94646. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94647. return true;
  94648. }
  94649. return false;
  94650. };
  94651. /**
  94652. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94653. * @param radiusDelta The delta by which to animate to. Can be negative.
  94654. */
  94655. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94656. var _this = this;
  94657. if (!this._attachedCamera) {
  94658. return;
  94659. }
  94660. if (!this._radiusBounceTransition) {
  94661. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94662. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94663. }
  94664. // Prevent zoom until bounce has completed
  94665. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94666. this._attachedCamera.wheelPrecision = Infinity;
  94667. this._attachedCamera.inertialRadiusOffset = 0;
  94668. // Animate to the radius limit
  94669. this.stopAllAnimations();
  94670. this._radiusIsAnimating = true;
  94671. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94672. if (animatable) {
  94673. this._animatables.push(animatable);
  94674. }
  94675. };
  94676. /**
  94677. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94678. */
  94679. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94680. this._radiusIsAnimating = false;
  94681. if (this._attachedCamera) {
  94682. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94683. }
  94684. };
  94685. /**
  94686. * Stops and removes all animations that have been applied to the camera
  94687. */
  94688. BouncingBehavior.prototype.stopAllAnimations = function () {
  94689. if (this._attachedCamera) {
  94690. this._attachedCamera.animations = [];
  94691. }
  94692. while (this._animatables.length) {
  94693. this._animatables[0].onAnimationEnd = null;
  94694. this._animatables[0].stop();
  94695. this._animatables.shift();
  94696. }
  94697. };
  94698. /**
  94699. * The easing function used by animations
  94700. */
  94701. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94702. /**
  94703. * The easing mode used by animations
  94704. */
  94705. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94706. return BouncingBehavior;
  94707. }());
  94708. BABYLON.BouncingBehavior = BouncingBehavior;
  94709. })(BABYLON || (BABYLON = {}));
  94710. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94711. var BABYLON;
  94712. (function (BABYLON) {
  94713. var AutoRotationBehavior = /** @class */ (function () {
  94714. function AutoRotationBehavior() {
  94715. this._zoomStopsAnimation = false;
  94716. this._idleRotationSpeed = 0.05;
  94717. this._idleRotationWaitTime = 2000;
  94718. this._idleRotationSpinupTime = 2000;
  94719. this._isPointerDown = false;
  94720. this._lastFrameTime = null;
  94721. this._lastInteractionTime = -Infinity;
  94722. this._cameraRotationSpeed = 0;
  94723. this._lastFrameRadius = 0;
  94724. }
  94725. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94726. get: function () {
  94727. return "AutoRotation";
  94728. },
  94729. enumerable: true,
  94730. configurable: true
  94731. });
  94732. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94733. /**
  94734. * Gets the flag that indicates if user zooming should stop animation.
  94735. */
  94736. get: function () {
  94737. return this._zoomStopsAnimation;
  94738. },
  94739. /**
  94740. * Sets the flag that indicates if user zooming should stop animation.
  94741. */
  94742. set: function (flag) {
  94743. this._zoomStopsAnimation = flag;
  94744. },
  94745. enumerable: true,
  94746. configurable: true
  94747. });
  94748. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94749. /**
  94750. * Gets the default speed at which the camera rotates around the model.
  94751. */
  94752. get: function () {
  94753. return this._idleRotationSpeed;
  94754. },
  94755. /**
  94756. * Sets the default speed at which the camera rotates around the model.
  94757. */
  94758. set: function (speed) {
  94759. this._idleRotationSpeed = speed;
  94760. },
  94761. enumerable: true,
  94762. configurable: true
  94763. });
  94764. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94765. /**
  94766. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94767. */
  94768. get: function () {
  94769. return this._idleRotationWaitTime;
  94770. },
  94771. /**
  94772. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94773. */
  94774. set: function (time) {
  94775. this._idleRotationWaitTime = time;
  94776. },
  94777. enumerable: true,
  94778. configurable: true
  94779. });
  94780. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94781. /**
  94782. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94783. */
  94784. get: function () {
  94785. return this._idleRotationSpinupTime;
  94786. },
  94787. /**
  94788. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94789. */
  94790. set: function (time) {
  94791. this._idleRotationSpinupTime = time;
  94792. },
  94793. enumerable: true,
  94794. configurable: true
  94795. });
  94796. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94797. /**
  94798. * Gets a value indicating if the camera is currently rotating because of this behavior
  94799. */
  94800. get: function () {
  94801. return Math.abs(this._cameraRotationSpeed) > 0;
  94802. },
  94803. enumerable: true,
  94804. configurable: true
  94805. });
  94806. AutoRotationBehavior.prototype.init = function () {
  94807. // Do notihng
  94808. };
  94809. AutoRotationBehavior.prototype.attach = function (camera) {
  94810. var _this = this;
  94811. this._attachedCamera = camera;
  94812. var scene = this._attachedCamera.getScene();
  94813. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94814. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94815. _this._isPointerDown = true;
  94816. return;
  94817. }
  94818. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94819. _this._isPointerDown = false;
  94820. }
  94821. });
  94822. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94823. var now = BABYLON.Tools.Now;
  94824. var dt = 0;
  94825. if (_this._lastFrameTime != null) {
  94826. dt = now - _this._lastFrameTime;
  94827. }
  94828. _this._lastFrameTime = now;
  94829. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94830. _this._applyUserInteraction();
  94831. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94832. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94833. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94834. // Step camera rotation by rotation speed
  94835. if (_this._attachedCamera) {
  94836. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94837. }
  94838. });
  94839. };
  94840. AutoRotationBehavior.prototype.detach = function () {
  94841. if (!this._attachedCamera) {
  94842. return;
  94843. }
  94844. var scene = this._attachedCamera.getScene();
  94845. if (this._onPrePointerObservableObserver) {
  94846. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94847. }
  94848. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94849. this._attachedCamera = null;
  94850. };
  94851. /**
  94852. * Returns true if user is scrolling.
  94853. * @return true if user is scrolling.
  94854. */
  94855. AutoRotationBehavior.prototype._userIsZooming = function () {
  94856. if (!this._attachedCamera) {
  94857. return false;
  94858. }
  94859. return this._attachedCamera.inertialRadiusOffset !== 0;
  94860. };
  94861. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94862. if (!this._attachedCamera) {
  94863. return false;
  94864. }
  94865. var zoomHasHitLimit = false;
  94866. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94867. zoomHasHitLimit = true;
  94868. }
  94869. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94870. this._lastFrameRadius = this._attachedCamera.radius;
  94871. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94872. };
  94873. /**
  94874. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94875. */
  94876. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94877. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94878. this._lastInteractionTime = BABYLON.Tools.Now;
  94879. }
  94880. };
  94881. // Tools
  94882. AutoRotationBehavior.prototype._userIsMoving = function () {
  94883. if (!this._attachedCamera) {
  94884. return false;
  94885. }
  94886. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94887. this._attachedCamera.inertialBetaOffset !== 0 ||
  94888. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94889. this._attachedCamera.inertialPanningX !== 0 ||
  94890. this._attachedCamera.inertialPanningY !== 0 ||
  94891. this._isPointerDown;
  94892. };
  94893. return AutoRotationBehavior;
  94894. }());
  94895. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94896. })(BABYLON || (BABYLON = {}));
  94897. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94898. var BABYLON;
  94899. (function (BABYLON) {
  94900. var NullEngineOptions = /** @class */ (function () {
  94901. function NullEngineOptions() {
  94902. this.renderWidth = 512;
  94903. this.renderHeight = 256;
  94904. this.textureSize = 512;
  94905. this.deterministicLockstep = false;
  94906. this.lockstepMaxSteps = 4;
  94907. }
  94908. return NullEngineOptions;
  94909. }());
  94910. BABYLON.NullEngineOptions = NullEngineOptions;
  94911. /**
  94912. * The null engine class provides support for headless version of babylon.js.
  94913. * This can be used in server side scenario or for testing purposes
  94914. */
  94915. var NullEngine = /** @class */ (function (_super) {
  94916. __extends(NullEngine, _super);
  94917. function NullEngine(options) {
  94918. if (options === void 0) { options = new NullEngineOptions(); }
  94919. var _this = _super.call(this, null) || this;
  94920. if (options.deterministicLockstep === undefined) {
  94921. options.deterministicLockstep = false;
  94922. }
  94923. if (options.lockstepMaxSteps === undefined) {
  94924. options.lockstepMaxSteps = 4;
  94925. }
  94926. _this._options = options;
  94927. // Init caps
  94928. // We consider we are on a webgl1 capable device
  94929. _this._caps = new BABYLON.EngineCapabilities();
  94930. _this._caps.maxTexturesImageUnits = 16;
  94931. _this._caps.maxVertexTextureImageUnits = 16;
  94932. _this._caps.maxTextureSize = 512;
  94933. _this._caps.maxCubemapTextureSize = 512;
  94934. _this._caps.maxRenderTextureSize = 512;
  94935. _this._caps.maxVertexAttribs = 16;
  94936. _this._caps.maxVaryingVectors = 16;
  94937. _this._caps.maxFragmentUniformVectors = 16;
  94938. _this._caps.maxVertexUniformVectors = 16;
  94939. // Extensions
  94940. _this._caps.standardDerivatives = false;
  94941. _this._caps.astc = null;
  94942. _this._caps.s3tc = null;
  94943. _this._caps.pvrtc = null;
  94944. _this._caps.etc1 = null;
  94945. _this._caps.etc2 = null;
  94946. _this._caps.textureAnisotropicFilterExtension = null;
  94947. _this._caps.maxAnisotropy = 0;
  94948. _this._caps.uintIndices = false;
  94949. _this._caps.fragmentDepthSupported = false;
  94950. _this._caps.highPrecisionShaderSupported = true;
  94951. _this._caps.colorBufferFloat = false;
  94952. _this._caps.textureFloat = false;
  94953. _this._caps.textureFloatLinearFiltering = false;
  94954. _this._caps.textureFloatRender = false;
  94955. _this._caps.textureHalfFloat = false;
  94956. _this._caps.textureHalfFloatLinearFiltering = false;
  94957. _this._caps.textureHalfFloatRender = false;
  94958. _this._caps.textureLOD = false;
  94959. _this._caps.drawBuffersExtension = false;
  94960. _this._caps.depthTextureExtension = false;
  94961. _this._caps.vertexArrayObject = false;
  94962. _this._caps.instancedArrays = false;
  94963. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94964. // Wrappers
  94965. if (typeof URL === "undefined") {
  94966. URL = {
  94967. createObjectURL: function () { },
  94968. revokeObjectURL: function () { }
  94969. };
  94970. }
  94971. if (typeof Blob === "undefined") {
  94972. Blob = function () { };
  94973. }
  94974. return _this;
  94975. }
  94976. NullEngine.prototype.isDeterministicLockStep = function () {
  94977. return this._options.deterministicLockstep;
  94978. };
  94979. NullEngine.prototype.getLockstepMaxSteps = function () {
  94980. return this._options.lockstepMaxSteps;
  94981. };
  94982. NullEngine.prototype.getHardwareScalingLevel = function () {
  94983. return 1.0;
  94984. };
  94985. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94986. return {
  94987. capacity: 0,
  94988. references: 1,
  94989. is32Bits: false
  94990. };
  94991. };
  94992. NullEngine.prototype.createIndexBuffer = function (indices) {
  94993. return {
  94994. capacity: 0,
  94995. references: 1,
  94996. is32Bits: false
  94997. };
  94998. };
  94999. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95000. if (stencil === void 0) { stencil = false; }
  95001. };
  95002. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95003. if (useScreen === void 0) { useScreen = false; }
  95004. if (!useScreen && this._currentRenderTarget) {
  95005. return this._currentRenderTarget.width;
  95006. }
  95007. return this._options.renderWidth;
  95008. };
  95009. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95010. if (useScreen === void 0) { useScreen = false; }
  95011. if (!useScreen && this._currentRenderTarget) {
  95012. return this._currentRenderTarget.height;
  95013. }
  95014. return this._options.renderHeight;
  95015. };
  95016. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95017. this._cachedViewport = viewport;
  95018. };
  95019. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95020. return {
  95021. transformFeedback: null,
  95022. __SPECTOR_rebuildProgram: null
  95023. };
  95024. };
  95025. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95026. return [];
  95027. };
  95028. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95029. return [];
  95030. };
  95031. NullEngine.prototype.bindSamplers = function (effect) {
  95032. this._currentEffect = null;
  95033. };
  95034. NullEngine.prototype.enableEffect = function (effect) {
  95035. this._currentEffect = effect;
  95036. if (effect.onBind) {
  95037. effect.onBind(effect);
  95038. }
  95039. effect.onBindObservable.notifyObservers(effect);
  95040. };
  95041. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95042. if (zOffset === void 0) { zOffset = 0; }
  95043. if (reverseSide === void 0) { reverseSide = false; }
  95044. };
  95045. NullEngine.prototype.setIntArray = function (uniform, array) {
  95046. };
  95047. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95048. };
  95049. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95050. };
  95051. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95052. };
  95053. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95054. };
  95055. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95056. };
  95057. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95058. };
  95059. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95060. };
  95061. NullEngine.prototype.setArray = function (uniform, array) {
  95062. };
  95063. NullEngine.prototype.setArray2 = function (uniform, array) {
  95064. };
  95065. NullEngine.prototype.setArray3 = function (uniform, array) {
  95066. };
  95067. NullEngine.prototype.setArray4 = function (uniform, array) {
  95068. };
  95069. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95070. };
  95071. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95072. };
  95073. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95074. };
  95075. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95076. };
  95077. NullEngine.prototype.setFloat = function (uniform, value) {
  95078. };
  95079. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95080. };
  95081. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95082. };
  95083. NullEngine.prototype.setBool = function (uniform, bool) {
  95084. };
  95085. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95086. };
  95087. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95088. };
  95089. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95090. };
  95091. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95092. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95093. if (this._alphaMode === mode) {
  95094. return;
  95095. }
  95096. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95097. if (!noDepthWriteChange) {
  95098. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95099. }
  95100. this._alphaMode = mode;
  95101. };
  95102. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95103. };
  95104. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95105. if (this.preventCacheWipeBetweenFrames) {
  95106. return;
  95107. }
  95108. this.resetTextureCache();
  95109. this._currentEffect = null;
  95110. if (bruteForce) {
  95111. this._currentProgram = null;
  95112. this._stencilState.reset();
  95113. this._depthCullingState.reset();
  95114. this._alphaState.reset();
  95115. }
  95116. this._cachedVertexBuffers = null;
  95117. this._cachedIndexBuffer = null;
  95118. this._cachedEffectForVertexBuffers = null;
  95119. };
  95120. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95121. };
  95122. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95123. };
  95124. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95125. };
  95126. NullEngine.prototype._createTexture = function () {
  95127. return {};
  95128. };
  95129. NullEngine.prototype._releaseTexture = function (texture) {
  95130. };
  95131. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95133. if (onLoad === void 0) { onLoad = null; }
  95134. if (onError === void 0) { onError = null; }
  95135. if (buffer === void 0) { buffer = null; }
  95136. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95137. var url = String(urlArg);
  95138. texture.url = url;
  95139. texture.generateMipMaps = !noMipmap;
  95140. texture.samplingMode = samplingMode;
  95141. texture.invertY = invertY;
  95142. texture.baseWidth = this._options.textureSize;
  95143. texture.baseHeight = this._options.textureSize;
  95144. texture.width = this._options.textureSize;
  95145. texture.height = this._options.textureSize;
  95146. if (format) {
  95147. texture.format = format;
  95148. }
  95149. texture.isReady = true;
  95150. if (onLoad) {
  95151. onLoad();
  95152. }
  95153. return texture;
  95154. };
  95155. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95156. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95157. if (options !== undefined && typeof options === "object") {
  95158. fullOptions.generateMipMaps = options.generateMipMaps;
  95159. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95160. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95161. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95162. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95163. }
  95164. else {
  95165. fullOptions.generateMipMaps = options;
  95166. fullOptions.generateDepthBuffer = true;
  95167. fullOptions.generateStencilBuffer = false;
  95168. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95169. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95170. }
  95171. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95172. var width = size.width || size;
  95173. var height = size.height || size;
  95174. texture._depthStencilBuffer = {};
  95175. texture._framebuffer = {};
  95176. texture.baseWidth = width;
  95177. texture.baseHeight = height;
  95178. texture.width = width;
  95179. texture.height = height;
  95180. texture.isReady = true;
  95181. texture.samples = 1;
  95182. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95183. texture.samplingMode = fullOptions.samplingMode;
  95184. texture.type = fullOptions.type;
  95185. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95186. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95187. return texture;
  95188. };
  95189. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95190. texture.samplingMode = samplingMode;
  95191. };
  95192. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95193. if (this._currentRenderTarget) {
  95194. this.unBindFramebuffer(this._currentRenderTarget);
  95195. }
  95196. this._currentRenderTarget = texture;
  95197. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95198. if (this._cachedViewport && !forceFullscreenViewport) {
  95199. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95200. }
  95201. };
  95202. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95203. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95204. this._currentRenderTarget = null;
  95205. if (onBeforeUnbind) {
  95206. if (texture._MSAAFramebuffer) {
  95207. this._currentFramebuffer = texture._framebuffer;
  95208. }
  95209. onBeforeUnbind();
  95210. }
  95211. this._currentFramebuffer = null;
  95212. };
  95213. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95214. var vbo = {
  95215. capacity: 1,
  95216. references: 1,
  95217. is32Bits: false
  95218. };
  95219. return vbo;
  95220. };
  95221. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95222. if (offset === void 0) { offset = 0; }
  95223. };
  95224. /**
  95225. * Updates a dynamic vertex buffer.
  95226. * @param vertexBuffer the vertex buffer to update
  95227. * @param data the data used to update the vertex buffer
  95228. * @param byteOffset the byte offset of the data (optional)
  95229. * @param byteLength the byte length of the data (optional)
  95230. */
  95231. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95232. };
  95233. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95234. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95235. this._boundTexturesCache[this._activeChannel] = texture;
  95236. }
  95237. };
  95238. NullEngine.prototype._bindTexture = function (channel, texture) {
  95239. if (channel < 0) {
  95240. return;
  95241. }
  95242. this._bindTextureDirectly(0, texture);
  95243. };
  95244. NullEngine.prototype._releaseBuffer = function (buffer) {
  95245. buffer.references--;
  95246. if (buffer.references === 0) {
  95247. return true;
  95248. }
  95249. return false;
  95250. };
  95251. NullEngine.prototype.releaseEffects = function () {
  95252. };
  95253. return NullEngine;
  95254. }(BABYLON.Engine));
  95255. BABYLON.NullEngine = NullEngine;
  95256. })(BABYLON || (BABYLON = {}));
  95257. //# sourceMappingURL=babylon.nullEngine.js.map
  95258. var BABYLON;
  95259. (function (BABYLON) {
  95260. /**
  95261. * This class can be used to get instrumentation data from a Babylon engine
  95262. */
  95263. var EngineInstrumentation = /** @class */ (function () {
  95264. function EngineInstrumentation(engine) {
  95265. this.engine = engine;
  95266. this._captureGPUFrameTime = false;
  95267. this._gpuFrameTime = new BABYLON.PerfCounter();
  95268. this._captureShaderCompilationTime = false;
  95269. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95270. // Observers
  95271. this._onBeginFrameObserver = null;
  95272. this._onEndFrameObserver = null;
  95273. this._onBeforeShaderCompilationObserver = null;
  95274. this._onAfterShaderCompilationObserver = null;
  95275. }
  95276. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95277. // Properties
  95278. /**
  95279. * Gets the perf counter used for GPU frame time
  95280. */
  95281. get: function () {
  95282. return this._gpuFrameTime;
  95283. },
  95284. enumerable: true,
  95285. configurable: true
  95286. });
  95287. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95288. /**
  95289. * Gets the GPU frame time capture status
  95290. */
  95291. get: function () {
  95292. return this._captureGPUFrameTime;
  95293. },
  95294. /**
  95295. * Enable or disable the GPU frame time capture
  95296. */
  95297. set: function (value) {
  95298. var _this = this;
  95299. if (value === this._captureGPUFrameTime) {
  95300. return;
  95301. }
  95302. this._captureGPUFrameTime = value;
  95303. if (value) {
  95304. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95305. if (!_this._gpuFrameTimeToken) {
  95306. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95307. }
  95308. });
  95309. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95310. if (!_this._gpuFrameTimeToken) {
  95311. return;
  95312. }
  95313. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95314. if (time > -1) {
  95315. _this._gpuFrameTimeToken = null;
  95316. _this._gpuFrameTime.fetchNewFrame();
  95317. _this._gpuFrameTime.addCount(time, true);
  95318. }
  95319. });
  95320. }
  95321. else {
  95322. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95323. this._onBeginFrameObserver = null;
  95324. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95325. this._onEndFrameObserver = null;
  95326. }
  95327. },
  95328. enumerable: true,
  95329. configurable: true
  95330. });
  95331. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95332. /**
  95333. * Gets the perf counter used for shader compilation time
  95334. */
  95335. get: function () {
  95336. return this._shaderCompilationTime;
  95337. },
  95338. enumerable: true,
  95339. configurable: true
  95340. });
  95341. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95342. /**
  95343. * Gets the shader compilation time capture status
  95344. */
  95345. get: function () {
  95346. return this._captureShaderCompilationTime;
  95347. },
  95348. /**
  95349. * Enable or disable the shader compilation time capture
  95350. */
  95351. set: function (value) {
  95352. var _this = this;
  95353. if (value === this._captureShaderCompilationTime) {
  95354. return;
  95355. }
  95356. this._captureShaderCompilationTime = value;
  95357. if (value) {
  95358. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95359. _this._shaderCompilationTime.fetchNewFrame();
  95360. _this._shaderCompilationTime.beginMonitoring();
  95361. });
  95362. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95363. _this._shaderCompilationTime.endMonitoring();
  95364. });
  95365. }
  95366. else {
  95367. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95368. this._onBeforeShaderCompilationObserver = null;
  95369. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95370. this._onAfterShaderCompilationObserver = null;
  95371. }
  95372. },
  95373. enumerable: true,
  95374. configurable: true
  95375. });
  95376. EngineInstrumentation.prototype.dispose = function () {
  95377. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95378. this._onBeginFrameObserver = null;
  95379. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95380. this._onEndFrameObserver = null;
  95381. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95382. this._onBeforeShaderCompilationObserver = null;
  95383. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95384. this._onAfterShaderCompilationObserver = null;
  95385. this.engine = null;
  95386. };
  95387. return EngineInstrumentation;
  95388. }());
  95389. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95390. })(BABYLON || (BABYLON = {}));
  95391. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95392. var BABYLON;
  95393. (function (BABYLON) {
  95394. /**
  95395. * This class can be used to get instrumentation data from a Babylon engine
  95396. */
  95397. var SceneInstrumentation = /** @class */ (function () {
  95398. function SceneInstrumentation(scene) {
  95399. var _this = this;
  95400. this.scene = scene;
  95401. this._captureActiveMeshesEvaluationTime = false;
  95402. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95403. this._captureRenderTargetsRenderTime = false;
  95404. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95405. this._captureFrameTime = false;
  95406. this._frameTime = new BABYLON.PerfCounter();
  95407. this._captureRenderTime = false;
  95408. this._renderTime = new BABYLON.PerfCounter();
  95409. this._captureInterFrameTime = false;
  95410. this._interFrameTime = new BABYLON.PerfCounter();
  95411. this._captureParticlesRenderTime = false;
  95412. this._particlesRenderTime = new BABYLON.PerfCounter();
  95413. this._captureSpritesRenderTime = false;
  95414. this._spritesRenderTime = new BABYLON.PerfCounter();
  95415. this._capturePhysicsTime = false;
  95416. this._physicsTime = new BABYLON.PerfCounter();
  95417. this._captureAnimationsTime = false;
  95418. this._animationsTime = new BABYLON.PerfCounter();
  95419. // Observers
  95420. this._onBeforeActiveMeshesEvaluationObserver = null;
  95421. this._onAfterActiveMeshesEvaluationObserver = null;
  95422. this._onBeforeRenderTargetsRenderObserver = null;
  95423. this._onAfterRenderTargetsRenderObserver = null;
  95424. this._onAfterRenderObserver = null;
  95425. this._onBeforeDrawPhaseObserver = null;
  95426. this._onAfterDrawPhaseObserver = null;
  95427. this._onBeforeAnimationsObserver = null;
  95428. this._onBeforeParticlesRenderingObserver = null;
  95429. this._onAfterParticlesRenderingObserver = null;
  95430. this._onBeforeSpritesRenderingObserver = null;
  95431. this._onAfterSpritesRenderingObserver = null;
  95432. this._onBeforePhysicsObserver = null;
  95433. this._onAfterPhysicsObserver = null;
  95434. this._onAfterAnimationsObserver = null;
  95435. // Before render
  95436. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95437. if (_this._captureActiveMeshesEvaluationTime) {
  95438. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95439. }
  95440. if (_this._captureRenderTargetsRenderTime) {
  95441. _this._renderTargetsRenderTime.fetchNewFrame();
  95442. }
  95443. if (_this._captureFrameTime) {
  95444. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95445. _this._frameTime.beginMonitoring();
  95446. }
  95447. if (_this._captureInterFrameTime) {
  95448. _this._interFrameTime.endMonitoring();
  95449. }
  95450. if (_this._captureParticlesRenderTime) {
  95451. _this._particlesRenderTime.fetchNewFrame();
  95452. }
  95453. if (_this._captureSpritesRenderTime) {
  95454. _this._spritesRenderTime.fetchNewFrame();
  95455. }
  95456. if (_this._captureAnimationsTime) {
  95457. _this._animationsTime.beginMonitoring();
  95458. }
  95459. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95460. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95461. });
  95462. // After render
  95463. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95464. if (_this._captureFrameTime) {
  95465. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95466. _this._frameTime.endMonitoring();
  95467. }
  95468. if (_this._captureRenderTime) {
  95469. _this._renderTime.endMonitoring(false);
  95470. }
  95471. if (_this._captureInterFrameTime) {
  95472. _this._interFrameTime.beginMonitoring();
  95473. }
  95474. });
  95475. }
  95476. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95477. // Properties
  95478. /**
  95479. * Gets the perf counter used for active meshes evaluation time
  95480. */
  95481. get: function () {
  95482. return this._activeMeshesEvaluationTime;
  95483. },
  95484. enumerable: true,
  95485. configurable: true
  95486. });
  95487. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95488. /**
  95489. * Gets the active meshes evaluation time capture status
  95490. */
  95491. get: function () {
  95492. return this._captureActiveMeshesEvaluationTime;
  95493. },
  95494. /**
  95495. * Enable or disable the active meshes evaluation time capture
  95496. */
  95497. set: function (value) {
  95498. var _this = this;
  95499. if (value === this._captureActiveMeshesEvaluationTime) {
  95500. return;
  95501. }
  95502. this._captureActiveMeshesEvaluationTime = value;
  95503. if (value) {
  95504. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95505. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95506. _this._activeMeshesEvaluationTime.beginMonitoring();
  95507. });
  95508. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95509. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95510. _this._activeMeshesEvaluationTime.endMonitoring();
  95511. });
  95512. }
  95513. else {
  95514. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95515. this._onBeforeActiveMeshesEvaluationObserver = null;
  95516. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95517. this._onAfterActiveMeshesEvaluationObserver = null;
  95518. }
  95519. },
  95520. enumerable: true,
  95521. configurable: true
  95522. });
  95523. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95524. /**
  95525. * Gets the perf counter used for render targets render time
  95526. */
  95527. get: function () {
  95528. return this._renderTargetsRenderTime;
  95529. },
  95530. enumerable: true,
  95531. configurable: true
  95532. });
  95533. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95534. /**
  95535. * Gets the render targets render time capture status
  95536. */
  95537. get: function () {
  95538. return this._captureRenderTargetsRenderTime;
  95539. },
  95540. /**
  95541. * Enable or disable the render targets render time capture
  95542. */
  95543. set: function (value) {
  95544. var _this = this;
  95545. if (value === this._captureRenderTargetsRenderTime) {
  95546. return;
  95547. }
  95548. this._captureRenderTargetsRenderTime = value;
  95549. if (value) {
  95550. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95551. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95552. _this._renderTargetsRenderTime.beginMonitoring();
  95553. });
  95554. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95555. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95556. _this._renderTargetsRenderTime.endMonitoring(false);
  95557. });
  95558. }
  95559. else {
  95560. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95561. this._onBeforeRenderTargetsRenderObserver = null;
  95562. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95563. this._onAfterRenderTargetsRenderObserver = null;
  95564. }
  95565. },
  95566. enumerable: true,
  95567. configurable: true
  95568. });
  95569. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95570. /**
  95571. * Gets the perf counter used for particles render time
  95572. */
  95573. get: function () {
  95574. return this._particlesRenderTime;
  95575. },
  95576. enumerable: true,
  95577. configurable: true
  95578. });
  95579. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95580. /**
  95581. * Gets the particles render time capture status
  95582. */
  95583. get: function () {
  95584. return this._captureParticlesRenderTime;
  95585. },
  95586. /**
  95587. * Enable or disable the particles render time capture
  95588. */
  95589. set: function (value) {
  95590. var _this = this;
  95591. if (value === this._captureParticlesRenderTime) {
  95592. return;
  95593. }
  95594. this._captureParticlesRenderTime = value;
  95595. if (value) {
  95596. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95597. BABYLON.Tools.StartPerformanceCounter("Particles");
  95598. _this._particlesRenderTime.beginMonitoring();
  95599. });
  95600. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95601. BABYLON.Tools.EndPerformanceCounter("Particles");
  95602. _this._particlesRenderTime.endMonitoring(false);
  95603. });
  95604. }
  95605. else {
  95606. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95607. this._onBeforeParticlesRenderingObserver = null;
  95608. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95609. this._onAfterParticlesRenderingObserver = null;
  95610. }
  95611. },
  95612. enumerable: true,
  95613. configurable: true
  95614. });
  95615. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95616. /**
  95617. * Gets the perf counter used for sprites render time
  95618. */
  95619. get: function () {
  95620. return this._spritesRenderTime;
  95621. },
  95622. enumerable: true,
  95623. configurable: true
  95624. });
  95625. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95626. /**
  95627. * Gets the sprites render time capture status
  95628. */
  95629. get: function () {
  95630. return this._captureSpritesRenderTime;
  95631. },
  95632. /**
  95633. * Enable or disable the sprites render time capture
  95634. */
  95635. set: function (value) {
  95636. var _this = this;
  95637. if (value === this._captureSpritesRenderTime) {
  95638. return;
  95639. }
  95640. this._captureSpritesRenderTime = value;
  95641. if (value) {
  95642. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95643. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95644. _this._spritesRenderTime.beginMonitoring();
  95645. });
  95646. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95647. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95648. _this._spritesRenderTime.endMonitoring(false);
  95649. });
  95650. }
  95651. else {
  95652. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95653. this._onBeforeSpritesRenderingObserver = null;
  95654. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95655. this._onAfterSpritesRenderingObserver = null;
  95656. }
  95657. },
  95658. enumerable: true,
  95659. configurable: true
  95660. });
  95661. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95662. /**
  95663. * Gets the perf counter used for physics time
  95664. */
  95665. get: function () {
  95666. return this._physicsTime;
  95667. },
  95668. enumerable: true,
  95669. configurable: true
  95670. });
  95671. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95672. /**
  95673. * Gets the physics time capture status
  95674. */
  95675. get: function () {
  95676. return this._capturePhysicsTime;
  95677. },
  95678. /**
  95679. * Enable or disable the physics time capture
  95680. */
  95681. set: function (value) {
  95682. var _this = this;
  95683. if (value === this._capturePhysicsTime) {
  95684. return;
  95685. }
  95686. this._capturePhysicsTime = value;
  95687. if (value) {
  95688. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95689. BABYLON.Tools.StartPerformanceCounter("Physics");
  95690. _this._physicsTime.beginMonitoring();
  95691. });
  95692. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95693. BABYLON.Tools.EndPerformanceCounter("Physics");
  95694. _this._physicsTime.endMonitoring();
  95695. });
  95696. }
  95697. else {
  95698. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95699. this._onBeforePhysicsObserver = null;
  95700. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95701. this._onAfterPhysicsObserver = null;
  95702. }
  95703. },
  95704. enumerable: true,
  95705. configurable: true
  95706. });
  95707. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95708. /**
  95709. * Gets the perf counter used for animations time
  95710. */
  95711. get: function () {
  95712. return this._animationsTime;
  95713. },
  95714. enumerable: true,
  95715. configurable: true
  95716. });
  95717. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95718. /**
  95719. * Gets the animations time capture status
  95720. */
  95721. get: function () {
  95722. return this._captureAnimationsTime;
  95723. },
  95724. /**
  95725. * Enable or disable the animations time capture
  95726. */
  95727. set: function (value) {
  95728. var _this = this;
  95729. if (value === this._captureAnimationsTime) {
  95730. return;
  95731. }
  95732. this._captureAnimationsTime = value;
  95733. if (value) {
  95734. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95735. _this._animationsTime.endMonitoring();
  95736. });
  95737. }
  95738. else {
  95739. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95740. this._onAfterAnimationsObserver = null;
  95741. }
  95742. },
  95743. enumerable: true,
  95744. configurable: true
  95745. });
  95746. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95747. /**
  95748. * Gets the perf counter used for frame time capture
  95749. */
  95750. get: function () {
  95751. return this._frameTime;
  95752. },
  95753. enumerable: true,
  95754. configurable: true
  95755. });
  95756. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95757. /**
  95758. * Gets the frame time capture status
  95759. */
  95760. get: function () {
  95761. return this._captureFrameTime;
  95762. },
  95763. /**
  95764. * Enable or disable the frame time capture
  95765. */
  95766. set: function (value) {
  95767. this._captureFrameTime = value;
  95768. },
  95769. enumerable: true,
  95770. configurable: true
  95771. });
  95772. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95773. /**
  95774. * Gets the perf counter used for inter-frames time capture
  95775. */
  95776. get: function () {
  95777. return this._interFrameTime;
  95778. },
  95779. enumerable: true,
  95780. configurable: true
  95781. });
  95782. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95783. /**
  95784. * Gets the inter-frames time capture status
  95785. */
  95786. get: function () {
  95787. return this._captureInterFrameTime;
  95788. },
  95789. /**
  95790. * Enable or disable the inter-frames time capture
  95791. */
  95792. set: function (value) {
  95793. this._captureInterFrameTime = value;
  95794. },
  95795. enumerable: true,
  95796. configurable: true
  95797. });
  95798. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95799. /**
  95800. * Gets the perf counter used for render time capture
  95801. */
  95802. get: function () {
  95803. return this._renderTime;
  95804. },
  95805. enumerable: true,
  95806. configurable: true
  95807. });
  95808. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95809. /**
  95810. * Gets the render time capture status
  95811. */
  95812. get: function () {
  95813. return this._captureRenderTime;
  95814. },
  95815. /**
  95816. * Enable or disable the render time capture
  95817. */
  95818. set: function (value) {
  95819. var _this = this;
  95820. if (value === this._captureRenderTime) {
  95821. return;
  95822. }
  95823. this._captureRenderTime = value;
  95824. if (value) {
  95825. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95826. _this._renderTime.beginMonitoring();
  95827. BABYLON.Tools.StartPerformanceCounter("Main render");
  95828. });
  95829. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95830. _this._renderTime.endMonitoring(false);
  95831. BABYLON.Tools.EndPerformanceCounter("Main render");
  95832. });
  95833. }
  95834. else {
  95835. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95836. this._onBeforeDrawPhaseObserver = null;
  95837. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95838. this._onAfterDrawPhaseObserver = null;
  95839. }
  95840. },
  95841. enumerable: true,
  95842. configurable: true
  95843. });
  95844. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95845. /**
  95846. * Gets the perf counter used for draw calls
  95847. */
  95848. get: function () {
  95849. return this.scene.getEngine()._drawCalls;
  95850. },
  95851. enumerable: true,
  95852. configurable: true
  95853. });
  95854. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95855. /**
  95856. * Gets the perf counter used for texture collisions
  95857. */
  95858. get: function () {
  95859. return this.scene.getEngine()._textureCollisions;
  95860. },
  95861. enumerable: true,
  95862. configurable: true
  95863. });
  95864. SceneInstrumentation.prototype.dispose = function () {
  95865. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95866. this._onAfterRenderObserver = null;
  95867. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95868. this._onBeforeActiveMeshesEvaluationObserver = null;
  95869. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95870. this._onAfterActiveMeshesEvaluationObserver = null;
  95871. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95872. this._onBeforeRenderTargetsRenderObserver = null;
  95873. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95874. this._onAfterRenderTargetsRenderObserver = null;
  95875. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95876. this._onBeforeAnimationsObserver = null;
  95877. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95878. this._onBeforeParticlesRenderingObserver = null;
  95879. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95880. this._onAfterParticlesRenderingObserver = null;
  95881. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95882. this._onBeforeSpritesRenderingObserver = null;
  95883. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95884. this._onAfterSpritesRenderingObserver = null;
  95885. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95886. this._onBeforeDrawPhaseObserver = null;
  95887. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95888. this._onAfterDrawPhaseObserver = null;
  95889. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95890. this._onBeforePhysicsObserver = null;
  95891. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95892. this._onAfterPhysicsObserver = null;
  95893. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95894. this._onAfterAnimationsObserver = null;
  95895. this.scene = null;
  95896. };
  95897. return SceneInstrumentation;
  95898. }());
  95899. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95900. })(BABYLON || (BABYLON = {}));
  95901. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95902. var BABYLON;
  95903. (function (BABYLON) {
  95904. /**
  95905. * @hidden
  95906. **/
  95907. var _TimeToken = /** @class */ (function () {
  95908. function _TimeToken() {
  95909. this._timeElapsedQueryEnded = false;
  95910. }
  95911. return _TimeToken;
  95912. }());
  95913. BABYLON._TimeToken = _TimeToken;
  95914. })(BABYLON || (BABYLON = {}));
  95915. //# sourceMappingURL=babylon.timeToken.js.map
  95916. var BABYLON;
  95917. (function (BABYLON) {
  95918. /**
  95919. * Background material defines definition.
  95920. * @hidden Mainly internal Use
  95921. */
  95922. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95923. __extends(BackgroundMaterialDefines, _super);
  95924. /**
  95925. * Constructor of the defines.
  95926. */
  95927. function BackgroundMaterialDefines() {
  95928. var _this = _super.call(this) || this;
  95929. /**
  95930. * True if the diffuse texture is in use.
  95931. */
  95932. _this.DIFFUSE = false;
  95933. /**
  95934. * The direct UV channel to use.
  95935. */
  95936. _this.DIFFUSEDIRECTUV = 0;
  95937. /**
  95938. * True if the diffuse texture is in gamma space.
  95939. */
  95940. _this.GAMMADIFFUSE = false;
  95941. /**
  95942. * True if the diffuse texture has opacity in the alpha channel.
  95943. */
  95944. _this.DIFFUSEHASALPHA = false;
  95945. /**
  95946. * True if you want the material to fade to transparent at grazing angle.
  95947. */
  95948. _this.OPACITYFRESNEL = false;
  95949. /**
  95950. * True if an extra blur needs to be added in the reflection.
  95951. */
  95952. _this.REFLECTIONBLUR = false;
  95953. /**
  95954. * True if you want the material to fade to reflection at grazing angle.
  95955. */
  95956. _this.REFLECTIONFRESNEL = false;
  95957. /**
  95958. * True if you want the material to falloff as far as you move away from the scene center.
  95959. */
  95960. _this.REFLECTIONFALLOFF = false;
  95961. /**
  95962. * False if the current Webgl implementation does not support the texture lod extension.
  95963. */
  95964. _this.TEXTURELODSUPPORT = false;
  95965. /**
  95966. * True to ensure the data are premultiplied.
  95967. */
  95968. _this.PREMULTIPLYALPHA = false;
  95969. /**
  95970. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95971. */
  95972. _this.USERGBCOLOR = false;
  95973. /**
  95974. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95975. * stays aligned with the desired configuration.
  95976. */
  95977. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95978. /**
  95979. * True to add noise in order to reduce the banding effect.
  95980. */
  95981. _this.NOISE = false;
  95982. /**
  95983. * is the reflection texture in BGR color scheme?
  95984. * Mainly used to solve a bug in ios10 video tag
  95985. */
  95986. _this.REFLECTIONBGR = false;
  95987. _this.IMAGEPROCESSING = false;
  95988. _this.VIGNETTE = false;
  95989. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95990. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95991. _this.TONEMAPPING = false;
  95992. _this.CONTRAST = false;
  95993. _this.COLORCURVES = false;
  95994. _this.COLORGRADING = false;
  95995. _this.COLORGRADING3D = false;
  95996. _this.SAMPLER3DGREENDEPTH = false;
  95997. _this.SAMPLER3DBGRMAP = false;
  95998. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95999. _this.EXPOSURE = false;
  96000. // Reflection.
  96001. _this.REFLECTION = false;
  96002. _this.REFLECTIONMAP_3D = false;
  96003. _this.REFLECTIONMAP_SPHERICAL = false;
  96004. _this.REFLECTIONMAP_PLANAR = false;
  96005. _this.REFLECTIONMAP_CUBIC = false;
  96006. _this.REFLECTIONMAP_PROJECTION = false;
  96007. _this.REFLECTIONMAP_SKYBOX = false;
  96008. _this.REFLECTIONMAP_EXPLICIT = false;
  96009. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96010. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96011. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96012. _this.INVERTCUBICMAP = false;
  96013. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96014. _this.LODINREFLECTIONALPHA = false;
  96015. _this.GAMMAREFLECTION = false;
  96016. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96017. // Default BJS.
  96018. _this.MAINUV1 = false;
  96019. _this.MAINUV2 = false;
  96020. _this.UV1 = false;
  96021. _this.UV2 = false;
  96022. _this.CLIPPLANE = false;
  96023. _this.POINTSIZE = false;
  96024. _this.FOG = false;
  96025. _this.NORMAL = false;
  96026. _this.NUM_BONE_INFLUENCERS = 0;
  96027. _this.BonesPerMesh = 0;
  96028. _this.INSTANCES = false;
  96029. _this.SHADOWFLOAT = false;
  96030. _this.rebuild();
  96031. return _this;
  96032. }
  96033. return BackgroundMaterialDefines;
  96034. }(BABYLON.MaterialDefines));
  96035. /**
  96036. * Background material used to create an efficient environement around your scene.
  96037. */
  96038. var BackgroundMaterial = /** @class */ (function (_super) {
  96039. __extends(BackgroundMaterial, _super);
  96040. /**
  96041. * Instantiates a Background Material in the given scene
  96042. * @param name The friendly name of the material
  96043. * @param scene The scene to add the material to
  96044. */
  96045. function BackgroundMaterial(name, scene) {
  96046. var _this = _super.call(this, name, scene) || this;
  96047. /**
  96048. * Key light Color (multiply against the environement texture)
  96049. */
  96050. _this.primaryColor = BABYLON.Color3.White();
  96051. _this._primaryColorShadowLevel = 0;
  96052. _this._primaryColorHighlightLevel = 0;
  96053. /**
  96054. * Reflection Texture used in the material.
  96055. * Should be author in a specific way for the best result (refer to the documentation).
  96056. */
  96057. _this.reflectionTexture = null;
  96058. /**
  96059. * Reflection Texture level of blur.
  96060. *
  96061. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96062. * texture twice.
  96063. */
  96064. _this.reflectionBlur = 0;
  96065. /**
  96066. * Diffuse Texture used in the material.
  96067. * Should be author in a specific way for the best result (refer to the documentation).
  96068. */
  96069. _this.diffuseTexture = null;
  96070. _this._shadowLights = null;
  96071. /**
  96072. * Specify the list of lights casting shadow on the material.
  96073. * All scene shadow lights will be included if null.
  96074. */
  96075. _this.shadowLights = null;
  96076. /**
  96077. * Helps adjusting the shadow to a softer level if required.
  96078. * 0 means black shadows and 1 means no shadows.
  96079. */
  96080. _this.shadowLevel = 0;
  96081. /**
  96082. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96083. * It is usually zero but might be interesting to modify according to your setup.
  96084. */
  96085. _this.sceneCenter = BABYLON.Vector3.Zero();
  96086. /**
  96087. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96088. * This helps ensuring a nice transition when the camera goes under the ground.
  96089. */
  96090. _this.opacityFresnel = true;
  96091. /**
  96092. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96093. * This helps adding a mirror texture on the ground.
  96094. */
  96095. _this.reflectionFresnel = false;
  96096. /**
  96097. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96098. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96099. */
  96100. _this.reflectionFalloffDistance = 0.0;
  96101. /**
  96102. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96103. */
  96104. _this.reflectionAmount = 1.0;
  96105. /**
  96106. * This specifies the weight of the reflection at grazing angle.
  96107. */
  96108. _this.reflectionReflectance0 = 0.05;
  96109. /**
  96110. * This specifies the weight of the reflection at a perpendicular point of view.
  96111. */
  96112. _this.reflectionReflectance90 = 0.5;
  96113. /**
  96114. * Helps to directly use the maps channels instead of their level.
  96115. */
  96116. _this.useRGBColor = true;
  96117. /**
  96118. * This helps reducing the banding effect that could occur on the background.
  96119. */
  96120. _this.enableNoise = false;
  96121. _this._fovMultiplier = 1.0;
  96122. /**
  96123. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96124. */
  96125. _this.useEquirectangularFOV = false;
  96126. _this._maxSimultaneousLights = 4;
  96127. /**
  96128. * Number of Simultaneous lights allowed on the material.
  96129. */
  96130. _this.maxSimultaneousLights = 4;
  96131. /**
  96132. * Keep track of the image processing observer to allow dispose and replace.
  96133. */
  96134. _this._imageProcessingObserver = null;
  96135. /**
  96136. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96137. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96138. */
  96139. _this.switchToBGR = false;
  96140. // Temp values kept as cache in the material.
  96141. _this._renderTargets = new BABYLON.SmartArray(16);
  96142. _this._reflectionControls = BABYLON.Vector4.Zero();
  96143. _this._white = BABYLON.Color3.White();
  96144. _this._primaryShadowColor = BABYLON.Color3.Black();
  96145. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96146. // Setup the default processing configuration to the scene.
  96147. _this._attachImageProcessingConfiguration(null);
  96148. _this.getRenderTargetTextures = function () {
  96149. _this._renderTargets.reset();
  96150. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96151. _this._renderTargets.push(_this._diffuseTexture);
  96152. }
  96153. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96154. _this._renderTargets.push(_this._reflectionTexture);
  96155. }
  96156. return _this._renderTargets;
  96157. };
  96158. return _this;
  96159. }
  96160. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96161. /**
  96162. * Experimental Internal Use Only.
  96163. *
  96164. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96165. * This acts as a helper to set the primary color to a more "human friendly" value.
  96166. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96167. * output color as close as possible from the chosen value.
  96168. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96169. * part of lighting setup.)
  96170. */
  96171. get: function () {
  96172. return this.__perceptualColor;
  96173. },
  96174. set: function (value) {
  96175. this.__perceptualColor = value;
  96176. this._computePrimaryColorFromPerceptualColor();
  96177. this._markAllSubMeshesAsLightsDirty();
  96178. },
  96179. enumerable: true,
  96180. configurable: true
  96181. });
  96182. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96183. /**
  96184. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96185. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96186. */
  96187. get: function () {
  96188. return this._primaryColorShadowLevel;
  96189. },
  96190. set: function (value) {
  96191. this._primaryColorShadowLevel = value;
  96192. this._computePrimaryColors();
  96193. this._markAllSubMeshesAsLightsDirty();
  96194. },
  96195. enumerable: true,
  96196. configurable: true
  96197. });
  96198. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96199. /**
  96200. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96201. * The primary color is used at the level chosen to define what the white area would look.
  96202. */
  96203. get: function () {
  96204. return this._primaryColorHighlightLevel;
  96205. },
  96206. set: function (value) {
  96207. this._primaryColorHighlightLevel = value;
  96208. this._computePrimaryColors();
  96209. this._markAllSubMeshesAsLightsDirty();
  96210. },
  96211. enumerable: true,
  96212. configurable: true
  96213. });
  96214. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96215. /**
  96216. * Sets the reflection reflectance fresnel values according to the default standard
  96217. * empirically know to work well :-)
  96218. */
  96219. set: function (value) {
  96220. var reflectionWeight = value;
  96221. if (reflectionWeight < 0.5) {
  96222. reflectionWeight = reflectionWeight * 2.0;
  96223. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96224. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96225. }
  96226. else {
  96227. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96228. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96229. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96230. }
  96231. },
  96232. enumerable: true,
  96233. configurable: true
  96234. });
  96235. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96236. /**
  96237. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96238. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96239. * Recommended to be keep at 1.0 except for special cases.
  96240. */
  96241. get: function () {
  96242. return this._fovMultiplier;
  96243. },
  96244. set: function (value) {
  96245. if (isNaN(value)) {
  96246. value = 1.0;
  96247. }
  96248. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96249. },
  96250. enumerable: true,
  96251. configurable: true
  96252. });
  96253. /**
  96254. * Attaches a new image processing configuration to the PBR Material.
  96255. * @param configuration (if null the scene configuration will be use)
  96256. */
  96257. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96258. var _this = this;
  96259. if (configuration === this._imageProcessingConfiguration) {
  96260. return;
  96261. }
  96262. // Detaches observer.
  96263. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96264. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96265. }
  96266. // Pick the scene configuration if needed.
  96267. if (!configuration) {
  96268. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96269. }
  96270. else {
  96271. this._imageProcessingConfiguration = configuration;
  96272. }
  96273. // Attaches observer.
  96274. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96275. _this._computePrimaryColorFromPerceptualColor();
  96276. _this._markAllSubMeshesAsImageProcessingDirty();
  96277. });
  96278. };
  96279. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96280. /**
  96281. * Gets the image processing configuration used either in this material.
  96282. */
  96283. get: function () {
  96284. return this._imageProcessingConfiguration;
  96285. },
  96286. /**
  96287. * Sets the Default image processing configuration used either in the this material.
  96288. *
  96289. * If sets to null, the scene one is in use.
  96290. */
  96291. set: function (value) {
  96292. this._attachImageProcessingConfiguration(value);
  96293. // Ensure the effect will be rebuilt.
  96294. this._markAllSubMeshesAsTexturesDirty();
  96295. },
  96296. enumerable: true,
  96297. configurable: true
  96298. });
  96299. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96300. /**
  96301. * Gets wether the color curves effect is enabled.
  96302. */
  96303. get: function () {
  96304. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96305. },
  96306. /**
  96307. * Sets wether the color curves effect is enabled.
  96308. */
  96309. set: function (value) {
  96310. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96311. },
  96312. enumerable: true,
  96313. configurable: true
  96314. });
  96315. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96316. /**
  96317. * Gets wether the color grading effect is enabled.
  96318. */
  96319. get: function () {
  96320. return this.imageProcessingConfiguration.colorGradingEnabled;
  96321. },
  96322. /**
  96323. * Gets wether the color grading effect is enabled.
  96324. */
  96325. set: function (value) {
  96326. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96327. },
  96328. enumerable: true,
  96329. configurable: true
  96330. });
  96331. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96332. /**
  96333. * Gets wether tonemapping is enabled or not.
  96334. */
  96335. get: function () {
  96336. return this._imageProcessingConfiguration.toneMappingEnabled;
  96337. },
  96338. /**
  96339. * Sets wether tonemapping is enabled or not
  96340. */
  96341. set: function (value) {
  96342. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96343. },
  96344. enumerable: true,
  96345. configurable: true
  96346. });
  96347. ;
  96348. ;
  96349. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96350. /**
  96351. * The camera exposure used on this material.
  96352. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96353. * This corresponds to a photographic exposure.
  96354. */
  96355. get: function () {
  96356. return this._imageProcessingConfiguration.exposure;
  96357. },
  96358. /**
  96359. * The camera exposure used on this material.
  96360. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96361. * This corresponds to a photographic exposure.
  96362. */
  96363. set: function (value) {
  96364. this._imageProcessingConfiguration.exposure = value;
  96365. },
  96366. enumerable: true,
  96367. configurable: true
  96368. });
  96369. ;
  96370. ;
  96371. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96372. /**
  96373. * Gets The camera contrast used on this material.
  96374. */
  96375. get: function () {
  96376. return this._imageProcessingConfiguration.contrast;
  96377. },
  96378. /**
  96379. * Sets The camera contrast used on this material.
  96380. */
  96381. set: function (value) {
  96382. this._imageProcessingConfiguration.contrast = value;
  96383. },
  96384. enumerable: true,
  96385. configurable: true
  96386. });
  96387. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96388. /**
  96389. * Gets the Color Grading 2D Lookup Texture.
  96390. */
  96391. get: function () {
  96392. return this._imageProcessingConfiguration.colorGradingTexture;
  96393. },
  96394. /**
  96395. * Sets the Color Grading 2D Lookup Texture.
  96396. */
  96397. set: function (value) {
  96398. this.imageProcessingConfiguration.colorGradingTexture = value;
  96399. },
  96400. enumerable: true,
  96401. configurable: true
  96402. });
  96403. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96404. /**
  96405. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96406. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96407. * 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;
  96408. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96409. */
  96410. get: function () {
  96411. return this.imageProcessingConfiguration.colorCurves;
  96412. },
  96413. /**
  96414. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96415. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96416. * 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;
  96417. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96418. */
  96419. set: function (value) {
  96420. this.imageProcessingConfiguration.colorCurves = value;
  96421. },
  96422. enumerable: true,
  96423. configurable: true
  96424. });
  96425. /**
  96426. * The entire material has been created in order to prevent overdraw.
  96427. * @returns false
  96428. */
  96429. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96430. return true;
  96431. };
  96432. /**
  96433. * The entire material has been created in order to prevent overdraw.
  96434. * @returns true if blending is enable
  96435. */
  96436. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96437. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96438. };
  96439. /**
  96440. * Checks wether the material is ready to be rendered for a given mesh.
  96441. * @param mesh The mesh to render
  96442. * @param subMesh The submesh to check against
  96443. * @param useInstances Specify wether or not the material is used with instances
  96444. * @returns true if all the dependencies are ready (Textures, Effects...)
  96445. */
  96446. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96447. var _this = this;
  96448. if (useInstances === void 0) { useInstances = false; }
  96449. if (subMesh.effect && this.isFrozen) {
  96450. if (this._wasPreviouslyReady) {
  96451. return true;
  96452. }
  96453. }
  96454. if (!subMesh._materialDefines) {
  96455. subMesh._materialDefines = new BackgroundMaterialDefines();
  96456. }
  96457. var scene = this.getScene();
  96458. var defines = subMesh._materialDefines;
  96459. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96460. if (defines._renderId === scene.getRenderId()) {
  96461. return true;
  96462. }
  96463. }
  96464. var engine = scene.getEngine();
  96465. // Lights
  96466. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96467. defines._needNormals = true;
  96468. // Textures
  96469. if (defines._areTexturesDirty) {
  96470. defines._needUVs = false;
  96471. if (scene.texturesEnabled) {
  96472. if (scene.getEngine().getCaps().textureLOD) {
  96473. defines.TEXTURELODSUPPORT = true;
  96474. }
  96475. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96476. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96477. return false;
  96478. }
  96479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96480. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96481. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96482. defines.OPACITYFRESNEL = this._opacityFresnel;
  96483. }
  96484. else {
  96485. defines.DIFFUSE = false;
  96486. defines.DIFFUSEHASALPHA = false;
  96487. defines.GAMMADIFFUSE = false;
  96488. defines.OPACITYFRESNEL = false;
  96489. }
  96490. var reflectionTexture = this._reflectionTexture;
  96491. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96492. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96493. return false;
  96494. }
  96495. defines.REFLECTION = true;
  96496. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96497. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96498. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96499. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96500. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96501. defines.REFLECTIONBGR = this.switchToBGR;
  96502. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96503. defines.INVERTCUBICMAP = true;
  96504. }
  96505. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96506. switch (reflectionTexture.coordinatesMode) {
  96507. case BABYLON.Texture.EXPLICIT_MODE:
  96508. defines.REFLECTIONMAP_EXPLICIT = true;
  96509. break;
  96510. case BABYLON.Texture.PLANAR_MODE:
  96511. defines.REFLECTIONMAP_PLANAR = true;
  96512. break;
  96513. case BABYLON.Texture.PROJECTION_MODE:
  96514. defines.REFLECTIONMAP_PROJECTION = true;
  96515. break;
  96516. case BABYLON.Texture.SKYBOX_MODE:
  96517. defines.REFLECTIONMAP_SKYBOX = true;
  96518. break;
  96519. case BABYLON.Texture.SPHERICAL_MODE:
  96520. defines.REFLECTIONMAP_SPHERICAL = true;
  96521. break;
  96522. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96523. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96524. break;
  96525. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96526. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96527. break;
  96528. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96529. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96530. break;
  96531. case BABYLON.Texture.CUBIC_MODE:
  96532. case BABYLON.Texture.INVCUBIC_MODE:
  96533. default:
  96534. defines.REFLECTIONMAP_CUBIC = true;
  96535. break;
  96536. }
  96537. if (this.reflectionFresnel) {
  96538. defines.REFLECTIONFRESNEL = true;
  96539. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96540. this._reflectionControls.x = this.reflectionAmount;
  96541. this._reflectionControls.y = this.reflectionReflectance0;
  96542. this._reflectionControls.z = this.reflectionReflectance90;
  96543. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96544. }
  96545. else {
  96546. defines.REFLECTIONFRESNEL = false;
  96547. defines.REFLECTIONFALLOFF = false;
  96548. }
  96549. }
  96550. else {
  96551. defines.REFLECTION = false;
  96552. defines.REFLECTIONFRESNEL = false;
  96553. defines.REFLECTIONFALLOFF = false;
  96554. defines.REFLECTIONBLUR = false;
  96555. defines.REFLECTIONMAP_3D = false;
  96556. defines.REFLECTIONMAP_SPHERICAL = false;
  96557. defines.REFLECTIONMAP_PLANAR = false;
  96558. defines.REFLECTIONMAP_CUBIC = false;
  96559. defines.REFLECTIONMAP_PROJECTION = false;
  96560. defines.REFLECTIONMAP_SKYBOX = false;
  96561. defines.REFLECTIONMAP_EXPLICIT = false;
  96562. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96563. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96564. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96565. defines.INVERTCUBICMAP = false;
  96566. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96567. defines.LODINREFLECTIONALPHA = false;
  96568. defines.GAMMAREFLECTION = false;
  96569. }
  96570. }
  96571. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96572. defines.USERGBCOLOR = this._useRGBColor;
  96573. defines.NOISE = this._enableNoise;
  96574. }
  96575. if (defines._areLightsDirty) {
  96576. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96577. }
  96578. if (defines._areImageProcessingDirty) {
  96579. if (!this._imageProcessingConfiguration.isReady()) {
  96580. return false;
  96581. }
  96582. this._imageProcessingConfiguration.prepareDefines(defines);
  96583. }
  96584. // Misc.
  96585. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96586. // Values that need to be evaluated on every frame
  96587. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96588. // Attribs
  96589. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96590. if (mesh) {
  96591. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96592. mesh.createNormals(true);
  96593. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96594. }
  96595. }
  96596. }
  96597. // Get correct effect
  96598. if (defines.isDirty) {
  96599. defines.markAsProcessed();
  96600. scene.resetCachedMaterial();
  96601. // Fallbacks
  96602. var fallbacks = new BABYLON.EffectFallbacks();
  96603. if (defines.FOG) {
  96604. fallbacks.addFallback(0, "FOG");
  96605. }
  96606. if (defines.POINTSIZE) {
  96607. fallbacks.addFallback(1, "POINTSIZE");
  96608. }
  96609. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96610. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96611. fallbacks.addCPUSkinningFallback(0, mesh);
  96612. }
  96613. //Attributes
  96614. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96615. if (defines.NORMAL) {
  96616. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96617. }
  96618. if (defines.UV1) {
  96619. attribs.push(BABYLON.VertexBuffer.UVKind);
  96620. }
  96621. if (defines.UV2) {
  96622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96623. }
  96624. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96625. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96626. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96627. "vFogInfos", "vFogColor", "pointSize",
  96628. "vClipPlane", "mBones",
  96629. "vPrimaryColor", "vPrimaryColorShadow",
  96630. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96631. "shadowLevel", "alpha",
  96632. "vBackgroundCenter", "vReflectionControl",
  96633. "vDiffuseInfos", "diffuseMatrix",
  96634. ];
  96635. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96636. var uniformBuffers = ["Material", "Scene"];
  96637. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96638. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96639. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96640. uniformsNames: uniforms,
  96641. uniformBuffersNames: uniformBuffers,
  96642. samplers: samplers,
  96643. defines: defines,
  96644. maxSimultaneousLights: this._maxSimultaneousLights
  96645. });
  96646. var onCompiled = function (effect) {
  96647. if (_this.onCompiled) {
  96648. _this.onCompiled(effect);
  96649. }
  96650. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96651. };
  96652. var join = defines.toString();
  96653. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96654. attributes: attribs,
  96655. uniformsNames: uniforms,
  96656. uniformBuffersNames: uniformBuffers,
  96657. samplers: samplers,
  96658. defines: join,
  96659. fallbacks: fallbacks,
  96660. onCompiled: onCompiled,
  96661. onError: this.onError,
  96662. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96663. }, engine), defines);
  96664. this.buildUniformLayout();
  96665. }
  96666. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96667. return false;
  96668. }
  96669. defines._renderId = scene.getRenderId();
  96670. this._wasPreviouslyReady = true;
  96671. return true;
  96672. };
  96673. /**
  96674. * Compute the primary color according to the chosen perceptual color.
  96675. */
  96676. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96677. if (!this.__perceptualColor) {
  96678. return;
  96679. }
  96680. this._primaryColor.copyFrom(this.__perceptualColor);
  96681. // Revert gamma space.
  96682. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96683. // Revert image processing configuration.
  96684. if (this._imageProcessingConfiguration) {
  96685. // Revert Exposure.
  96686. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96687. }
  96688. this._computePrimaryColors();
  96689. };
  96690. /**
  96691. * Compute the highlights and shadow colors according to their chosen levels.
  96692. */
  96693. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96694. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96695. return;
  96696. }
  96697. // Find the highlight color based on the configuration.
  96698. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96699. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96700. // Find the shadow color based on the configuration.
  96701. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96702. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96703. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96704. };
  96705. /**
  96706. * Build the uniform buffer used in the material.
  96707. */
  96708. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96709. // Order is important !
  96710. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96711. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96712. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96713. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96714. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96715. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96716. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96717. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96718. this._uniformBuffer.addUniform("pointSize", 1);
  96719. this._uniformBuffer.addUniform("shadowLevel", 1);
  96720. this._uniformBuffer.addUniform("alpha", 1);
  96721. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96722. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96723. this._uniformBuffer.create();
  96724. };
  96725. /**
  96726. * Unbind the material.
  96727. */
  96728. BackgroundMaterial.prototype.unbind = function () {
  96729. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96730. this._uniformBuffer.setTexture("diffuseSampler", null);
  96731. }
  96732. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96733. this._uniformBuffer.setTexture("reflectionSampler", null);
  96734. }
  96735. _super.prototype.unbind.call(this);
  96736. };
  96737. /**
  96738. * Bind only the world matrix to the material.
  96739. * @param world The world matrix to bind.
  96740. */
  96741. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96742. this._activeEffect.setMatrix("world", world);
  96743. };
  96744. /**
  96745. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96746. * @param world The world matrix to bind.
  96747. * @param subMesh The submesh to bind for.
  96748. */
  96749. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96750. var scene = this.getScene();
  96751. var defines = subMesh._materialDefines;
  96752. if (!defines) {
  96753. return;
  96754. }
  96755. var effect = subMesh.effect;
  96756. if (!effect) {
  96757. return;
  96758. }
  96759. this._activeEffect = effect;
  96760. // Matrices
  96761. this.bindOnlyWorldMatrix(world);
  96762. // Bones
  96763. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96764. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96765. if (mustRebind) {
  96766. this._uniformBuffer.bindToEffect(effect, "Material");
  96767. this.bindViewProjection(effect);
  96768. var reflectionTexture = this._reflectionTexture;
  96769. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96770. // Texture uniforms
  96771. if (scene.texturesEnabled) {
  96772. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96773. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96774. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96775. }
  96776. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96777. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96778. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96779. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96780. }
  96781. }
  96782. if (this.shadowLevel > 0) {
  96783. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96784. }
  96785. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96786. // Point size
  96787. if (this.pointsCloud) {
  96788. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96789. }
  96790. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96791. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96792. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96793. }
  96794. else {
  96795. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96796. }
  96797. }
  96798. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96799. // Textures
  96800. if (scene.texturesEnabled) {
  96801. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96802. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96803. }
  96804. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96805. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96806. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96807. }
  96808. else if (!defines.REFLECTIONBLUR) {
  96809. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96810. }
  96811. else {
  96812. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96813. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96814. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96815. }
  96816. if (defines.REFLECTIONFRESNEL) {
  96817. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96818. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96819. }
  96820. }
  96821. }
  96822. // Clip plane
  96823. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96824. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96825. }
  96826. if (mustRebind || !this.isFrozen) {
  96827. if (scene.lightsEnabled) {
  96828. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96829. }
  96830. // View
  96831. this.bindView(effect);
  96832. // Fog
  96833. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96834. // image processing
  96835. this._imageProcessingConfiguration.bind(this._activeEffect);
  96836. }
  96837. this._uniformBuffer.update();
  96838. this._afterBind(mesh);
  96839. };
  96840. /**
  96841. * Dispose the material.
  96842. * @param forceDisposeEffect Force disposal of the associated effect.
  96843. * @param forceDisposeTextures Force disposal of the associated textures.
  96844. */
  96845. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96846. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96847. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96848. if (forceDisposeTextures) {
  96849. if (this.diffuseTexture) {
  96850. this.diffuseTexture.dispose();
  96851. }
  96852. if (this.reflectionTexture) {
  96853. this.reflectionTexture.dispose();
  96854. }
  96855. }
  96856. this._renderTargets.dispose();
  96857. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96858. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96859. }
  96860. _super.prototype.dispose.call(this, forceDisposeEffect);
  96861. };
  96862. /**
  96863. * Clones the material.
  96864. * @param name The cloned name.
  96865. * @returns The cloned material.
  96866. */
  96867. BackgroundMaterial.prototype.clone = function (name) {
  96868. var _this = this;
  96869. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96870. };
  96871. /**
  96872. * Serializes the current material to its JSON representation.
  96873. * @returns The JSON representation.
  96874. */
  96875. BackgroundMaterial.prototype.serialize = function () {
  96876. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96877. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96878. return serializationObject;
  96879. };
  96880. /**
  96881. * Gets the class name of the material
  96882. * @returns "BackgroundMaterial"
  96883. */
  96884. BackgroundMaterial.prototype.getClassName = function () {
  96885. return "BackgroundMaterial";
  96886. };
  96887. /**
  96888. * Parse a JSON input to create back a background material.
  96889. * @param source The JSON data to parse
  96890. * @param scene The scene to create the parsed material in
  96891. * @param rootUrl The root url of the assets the material depends upon
  96892. * @returns the instantiated BackgroundMaterial.
  96893. */
  96894. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96895. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96896. };
  96897. /**
  96898. * Standard reflectance value at parallel view angle.
  96899. */
  96900. BackgroundMaterial.StandardReflectance0 = 0.05;
  96901. /**
  96902. * Standard reflectance value at grazing angle.
  96903. */
  96904. BackgroundMaterial.StandardReflectance90 = 0.5;
  96905. __decorate([
  96906. BABYLON.serializeAsColor3()
  96907. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96908. __decorate([
  96909. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96910. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96911. __decorate([
  96912. BABYLON.serializeAsColor3()
  96913. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96914. __decorate([
  96915. BABYLON.serialize()
  96916. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96917. __decorate([
  96918. BABYLON.serialize()
  96919. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96920. __decorate([
  96921. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96922. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96923. __decorate([
  96924. BABYLON.serializeAsTexture()
  96925. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96926. __decorate([
  96927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96928. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96929. __decorate([
  96930. BABYLON.serialize()
  96931. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96932. __decorate([
  96933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96934. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96935. __decorate([
  96936. BABYLON.serializeAsTexture()
  96937. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96938. __decorate([
  96939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96940. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96941. __decorate([
  96942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96943. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96944. __decorate([
  96945. BABYLON.serialize()
  96946. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96947. __decorate([
  96948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96949. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96950. __decorate([
  96951. BABYLON.serializeAsVector3()
  96952. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96953. __decorate([
  96954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96955. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96956. __decorate([
  96957. BABYLON.serialize()
  96958. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96959. __decorate([
  96960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96961. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96962. __decorate([
  96963. BABYLON.serialize()
  96964. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96965. __decorate([
  96966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96967. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96968. __decorate([
  96969. BABYLON.serialize()
  96970. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96971. __decorate([
  96972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96973. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96974. __decorate([
  96975. BABYLON.serialize()
  96976. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96977. __decorate([
  96978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96979. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96980. __decorate([
  96981. BABYLON.serialize()
  96982. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96983. __decorate([
  96984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96985. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96986. __decorate([
  96987. BABYLON.serialize()
  96988. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96989. __decorate([
  96990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96991. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96992. __decorate([
  96993. BABYLON.serialize()
  96994. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96995. __decorate([
  96996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96997. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96998. __decorate([
  96999. BABYLON.serialize()
  97000. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97001. __decorate([
  97002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97003. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97004. __decorate([
  97005. BABYLON.serialize()
  97006. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97007. __decorate([
  97008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97009. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97010. __decorate([
  97011. BABYLON.serializeAsImageProcessingConfiguration()
  97012. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97013. return BackgroundMaterial;
  97014. }(BABYLON.PushMaterial));
  97015. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97016. })(BABYLON || (BABYLON = {}));
  97017. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97018. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97019. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97020. s = arguments[i];
  97021. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97022. t[p] = s[p];
  97023. }
  97024. return t;
  97025. };
  97026. var BABYLON;
  97027. (function (BABYLON) {
  97028. /**
  97029. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97030. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97031. * It also helps with the default setup of your imageProcessing configuration.
  97032. */
  97033. var EnvironmentHelper = /** @class */ (function () {
  97034. /**
  97035. * constructor
  97036. * @param options
  97037. * @param scene The scene to add the material to
  97038. */
  97039. function EnvironmentHelper(options, scene) {
  97040. var _this = this;
  97041. this._errorHandler = function (message, exception) {
  97042. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97043. };
  97044. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97045. this._scene = scene;
  97046. this.onErrorObservable = new BABYLON.Observable();
  97047. this._setupBackground();
  97048. this._setupImageProcessing();
  97049. }
  97050. /**
  97051. * Creates the default options for the helper.
  97052. */
  97053. EnvironmentHelper._getDefaultOptions = function () {
  97054. return {
  97055. createGround: true,
  97056. groundSize: 15,
  97057. groundTexture: this._groundTextureCDNUrl,
  97058. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97059. groundOpacity: 0.9,
  97060. enableGroundShadow: true,
  97061. groundShadowLevel: 0.5,
  97062. enableGroundMirror: false,
  97063. groundMirrorSizeRatio: 0.3,
  97064. groundMirrorBlurKernel: 64,
  97065. groundMirrorAmount: 1,
  97066. groundMirrorFresnelWeight: 1,
  97067. groundMirrorFallOffDistance: 0,
  97068. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97069. groundYBias: 0.00001,
  97070. createSkybox: true,
  97071. skyboxSize: 20,
  97072. skyboxTexture: this._skyboxTextureCDNUrl,
  97073. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97074. backgroundYRotation: 0,
  97075. sizeAuto: true,
  97076. rootPosition: BABYLON.Vector3.Zero(),
  97077. setupImageProcessing: true,
  97078. environmentTexture: this._environmentTextureCDNUrl,
  97079. cameraExposure: 0.8,
  97080. cameraContrast: 1.2,
  97081. toneMappingEnabled: true,
  97082. };
  97083. };
  97084. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97085. /**
  97086. * Gets the root mesh created by the helper.
  97087. */
  97088. get: function () {
  97089. return this._rootMesh;
  97090. },
  97091. enumerable: true,
  97092. configurable: true
  97093. });
  97094. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97095. /**
  97096. * Gets the skybox created by the helper.
  97097. */
  97098. get: function () {
  97099. return this._skybox;
  97100. },
  97101. enumerable: true,
  97102. configurable: true
  97103. });
  97104. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97105. /**
  97106. * Gets the skybox texture created by the helper.
  97107. */
  97108. get: function () {
  97109. return this._skyboxTexture;
  97110. },
  97111. enumerable: true,
  97112. configurable: true
  97113. });
  97114. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97115. /**
  97116. * Gets the skybox material created by the helper.
  97117. */
  97118. get: function () {
  97119. return this._skyboxMaterial;
  97120. },
  97121. enumerable: true,
  97122. configurable: true
  97123. });
  97124. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97125. /**
  97126. * Gets the ground mesh created by the helper.
  97127. */
  97128. get: function () {
  97129. return this._ground;
  97130. },
  97131. enumerable: true,
  97132. configurable: true
  97133. });
  97134. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97135. /**
  97136. * Gets the ground texture created by the helper.
  97137. */
  97138. get: function () {
  97139. return this._groundTexture;
  97140. },
  97141. enumerable: true,
  97142. configurable: true
  97143. });
  97144. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97145. /**
  97146. * Gets the ground mirror created by the helper.
  97147. */
  97148. get: function () {
  97149. return this._groundMirror;
  97150. },
  97151. enumerable: true,
  97152. configurable: true
  97153. });
  97154. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97155. /**
  97156. * Gets the ground mirror render list to helps pushing the meshes
  97157. * you wish in the ground reflection.
  97158. */
  97159. get: function () {
  97160. if (this._groundMirror) {
  97161. return this._groundMirror.renderList;
  97162. }
  97163. return null;
  97164. },
  97165. enumerable: true,
  97166. configurable: true
  97167. });
  97168. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97169. /**
  97170. * Gets the ground material created by the helper.
  97171. */
  97172. get: function () {
  97173. return this._groundMaterial;
  97174. },
  97175. enumerable: true,
  97176. configurable: true
  97177. });
  97178. /**
  97179. * Updates the background according to the new options
  97180. * @param options
  97181. */
  97182. EnvironmentHelper.prototype.updateOptions = function (options) {
  97183. var newOptions = __assign({}, this._options, options);
  97184. if (this._ground && !newOptions.createGround) {
  97185. this._ground.dispose();
  97186. this._ground = null;
  97187. }
  97188. if (this._groundMaterial && !newOptions.createGround) {
  97189. this._groundMaterial.dispose();
  97190. this._groundMaterial = null;
  97191. }
  97192. if (this._groundTexture) {
  97193. if (this._options.groundTexture != newOptions.groundTexture) {
  97194. this._groundTexture.dispose();
  97195. this._groundTexture = null;
  97196. }
  97197. }
  97198. if (this._skybox && !newOptions.createSkybox) {
  97199. this._skybox.dispose();
  97200. this._skybox = null;
  97201. }
  97202. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97203. this._skyboxMaterial.dispose();
  97204. this._skyboxMaterial = null;
  97205. }
  97206. if (this._skyboxTexture) {
  97207. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97208. this._skyboxTexture.dispose();
  97209. this._skyboxTexture = null;
  97210. }
  97211. }
  97212. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97213. this._groundMirror.dispose();
  97214. this._groundMirror = null;
  97215. }
  97216. if (this._scene.environmentTexture) {
  97217. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97218. this._scene.environmentTexture.dispose();
  97219. }
  97220. }
  97221. this._options = newOptions;
  97222. this._setupBackground();
  97223. this._setupImageProcessing();
  97224. };
  97225. /**
  97226. * Sets the primary color of all the available elements.
  97227. * @param color the main color to affect to the ground and the background
  97228. */
  97229. EnvironmentHelper.prototype.setMainColor = function (color) {
  97230. if (this.groundMaterial) {
  97231. this.groundMaterial.primaryColor = color;
  97232. }
  97233. if (this.skyboxMaterial) {
  97234. this.skyboxMaterial.primaryColor = color;
  97235. }
  97236. if (this.groundMirror) {
  97237. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97238. }
  97239. };
  97240. /**
  97241. * Setup the image processing according to the specified options.
  97242. */
  97243. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97244. if (this._options.setupImageProcessing) {
  97245. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97246. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97247. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97248. this._setupEnvironmentTexture();
  97249. }
  97250. };
  97251. /**
  97252. * Setup the environment texture according to the specified options.
  97253. */
  97254. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97255. if (this._scene.environmentTexture) {
  97256. return;
  97257. }
  97258. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97259. this._scene.environmentTexture = this._options.environmentTexture;
  97260. return;
  97261. }
  97262. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97263. this._scene.environmentTexture = environmentTexture;
  97264. };
  97265. /**
  97266. * Setup the background according to the specified options.
  97267. */
  97268. EnvironmentHelper.prototype._setupBackground = function () {
  97269. if (!this._rootMesh) {
  97270. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97271. }
  97272. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97273. var sceneSize = this._getSceneSize();
  97274. if (this._options.createGround) {
  97275. this._setupGround(sceneSize);
  97276. this._setupGroundMaterial();
  97277. this._setupGroundDiffuseTexture();
  97278. if (this._options.enableGroundMirror) {
  97279. this._setupGroundMirrorTexture(sceneSize);
  97280. }
  97281. this._setupMirrorInGroundMaterial();
  97282. }
  97283. if (this._options.createSkybox) {
  97284. this._setupSkybox(sceneSize);
  97285. this._setupSkyboxMaterial();
  97286. this._setupSkyboxReflectionTexture();
  97287. }
  97288. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97289. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97290. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97291. };
  97292. /**
  97293. * Get the scene sizes according to the setup.
  97294. */
  97295. EnvironmentHelper.prototype._getSceneSize = function () {
  97296. var _this = this;
  97297. var groundSize = this._options.groundSize;
  97298. var skyboxSize = this._options.skyboxSize;
  97299. var rootPosition = this._options.rootPosition;
  97300. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97301. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97302. }
  97303. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97304. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97305. });
  97306. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97307. if (this._options.sizeAuto) {
  97308. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97309. this._scene.activeCamera.upperRadiusLimit) {
  97310. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97311. skyboxSize = groundSize;
  97312. }
  97313. var sceneDiagonalLenght = sceneDiagonal.length();
  97314. if (sceneDiagonalLenght > groundSize) {
  97315. groundSize = sceneDiagonalLenght * 2;
  97316. skyboxSize = groundSize;
  97317. }
  97318. // 10 % bigger.
  97319. groundSize *= 1.1;
  97320. skyboxSize *= 1.5;
  97321. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97322. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97323. }
  97324. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97325. };
  97326. /**
  97327. * Setup the ground according to the specified options.
  97328. */
  97329. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97330. var _this = this;
  97331. if (!this._ground) {
  97332. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97333. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97334. this._ground.parent = this._rootMesh;
  97335. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97336. }
  97337. this._ground.receiveShadows = this._options.enableGroundShadow;
  97338. };
  97339. /**
  97340. * Setup the ground material according to the specified options.
  97341. */
  97342. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97343. if (!this._groundMaterial) {
  97344. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97345. }
  97346. this._groundMaterial.alpha = this._options.groundOpacity;
  97347. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97348. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97349. this._groundMaterial.primaryColor = this._options.groundColor;
  97350. this._groundMaterial.useRGBColor = false;
  97351. this._groundMaterial.enableNoise = true;
  97352. if (this._ground) {
  97353. this._ground.material = this._groundMaterial;
  97354. }
  97355. };
  97356. /**
  97357. * Setup the ground diffuse texture according to the specified options.
  97358. */
  97359. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97360. if (!this._groundMaterial) {
  97361. return;
  97362. }
  97363. if (this._groundTexture) {
  97364. return;
  97365. }
  97366. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97367. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97368. return;
  97369. }
  97370. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97371. diffuseTexture.gammaSpace = false;
  97372. diffuseTexture.hasAlpha = true;
  97373. this._groundMaterial.diffuseTexture = diffuseTexture;
  97374. };
  97375. /**
  97376. * Setup the ground mirror texture according to the specified options.
  97377. */
  97378. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97379. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97380. if (!this._groundMirror) {
  97381. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97382. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97383. this._groundMirror.anisotropicFilteringLevel = 1;
  97384. this._groundMirror.wrapU = wrapping;
  97385. this._groundMirror.wrapV = wrapping;
  97386. this._groundMirror.gammaSpace = false;
  97387. if (this._groundMirror.renderList) {
  97388. for (var i = 0; i < this._scene.meshes.length; i++) {
  97389. var mesh = this._scene.meshes[i];
  97390. if (mesh !== this._ground &&
  97391. mesh !== this._skybox &&
  97392. mesh !== this._rootMesh) {
  97393. this._groundMirror.renderList.push(mesh);
  97394. }
  97395. }
  97396. }
  97397. }
  97398. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97399. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97400. };
  97401. /**
  97402. * Setup the ground to receive the mirror texture.
  97403. */
  97404. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97405. if (this._groundMaterial) {
  97406. this._groundMaterial.reflectionTexture = this._groundMirror;
  97407. this._groundMaterial.reflectionFresnel = true;
  97408. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97409. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97410. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97411. }
  97412. };
  97413. /**
  97414. * Setup the skybox according to the specified options.
  97415. */
  97416. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97417. var _this = this;
  97418. if (!this._skybox) {
  97419. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97420. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97421. }
  97422. this._skybox.parent = this._rootMesh;
  97423. };
  97424. /**
  97425. * Setup the skybox material according to the specified options.
  97426. */
  97427. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97428. if (!this._skybox) {
  97429. return;
  97430. }
  97431. if (!this._skyboxMaterial) {
  97432. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97433. }
  97434. this._skyboxMaterial.useRGBColor = false;
  97435. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97436. this._skyboxMaterial.enableNoise = true;
  97437. this._skybox.material = this._skyboxMaterial;
  97438. };
  97439. /**
  97440. * Setup the skybox reflection texture according to the specified options.
  97441. */
  97442. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97443. if (!this._skyboxMaterial) {
  97444. return;
  97445. }
  97446. if (this._skyboxTexture) {
  97447. return;
  97448. }
  97449. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97450. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97451. return;
  97452. }
  97453. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97454. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97455. this._skyboxTexture.gammaSpace = false;
  97456. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97457. };
  97458. /**
  97459. * Dispose all the elements created by the Helper.
  97460. */
  97461. EnvironmentHelper.prototype.dispose = function () {
  97462. if (this._groundMaterial) {
  97463. this._groundMaterial.dispose(true, true);
  97464. }
  97465. if (this._skyboxMaterial) {
  97466. this._skyboxMaterial.dispose(true, true);
  97467. }
  97468. this._rootMesh.dispose(false);
  97469. };
  97470. /**
  97471. * Default ground texture URL.
  97472. */
  97473. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97474. /**
  97475. * Default skybox texture URL.
  97476. */
  97477. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97478. /**
  97479. * Default environment texture URL.
  97480. */
  97481. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97482. return EnvironmentHelper;
  97483. }());
  97484. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97485. })(BABYLON || (BABYLON = {}));
  97486. //# sourceMappingURL=babylon.environmentHelper.js.map
  97487. var BABYLON;
  97488. (function (BABYLON) {
  97489. /**
  97490. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97491. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97492. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97493. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97494. */
  97495. var VideoDome = /** @class */ (function (_super) {
  97496. __extends(VideoDome, _super);
  97497. /**
  97498. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97499. * @param name Element's name, child elements will append suffixes for their own names.
  97500. * @param urlsOrVideo
  97501. * @param options An object containing optional or exposed sub element properties:
  97502. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97503. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97504. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97505. * @param options **loop=true** Automatically loop video on end.
  97506. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97507. */
  97508. function VideoDome(name, urlsOrVideo, options, scene) {
  97509. var _this = _super.call(this, name, scene) || this;
  97510. // set defaults and manage values
  97511. name = name || "videoDome";
  97512. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97513. options.clickToPlay = Boolean(options.clickToPlay);
  97514. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97515. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97516. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97517. // create
  97518. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97519. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97520. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97521. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97522. flat: false,
  97523. radius: options.size,
  97524. subdivisions: options.resolution,
  97525. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97526. }, scene);
  97527. // configure material
  97528. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97529. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97530. material.reflectionTexture = _this._videoTexture;
  97531. material.useEquirectangularFOV = true;
  97532. material.fovMultiplier = 1.0;
  97533. // configure mesh
  97534. _this._mesh.material = material;
  97535. _this._mesh.parent = _this;
  97536. // optional configuration
  97537. if (options.clickToPlay) {
  97538. scene.onPointerUp = function () {
  97539. _this._videoTexture.video.play();
  97540. };
  97541. }
  97542. return _this;
  97543. }
  97544. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97545. /**
  97546. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97547. * Also see the options.resolution property.
  97548. */
  97549. get: function () {
  97550. return this._material.fovMultiplier;
  97551. },
  97552. set: function (value) {
  97553. this._material.fovMultiplier = value;
  97554. },
  97555. enumerable: true,
  97556. configurable: true
  97557. });
  97558. /**
  97559. * Releases resources associated with this node.
  97560. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97561. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97562. */
  97563. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97564. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97565. this._videoTexture.dispose();
  97566. this._mesh.dispose();
  97567. this._material.dispose();
  97568. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97569. };
  97570. return VideoDome;
  97571. }(BABYLON.Node));
  97572. BABYLON.VideoDome = VideoDome;
  97573. })(BABYLON || (BABYLON = {}));
  97574. //# sourceMappingURL=babylon.videoDome.js.map
  97575. 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; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\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"};
  97576. 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};"};
  97577. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97578. globalObject["BABYLON"] = BABYLON;
  97579. //backwards compatibility
  97580. if(typeof earcut !== 'undefined') {
  97581. globalObject["Earcut"] = {
  97582. earcut: earcut
  97583. };
  97584. }
  97585. return BABYLON;
  97586. });